How to pass values from foreach to view in codeigniter - php

How can I loop values in controller send it to view in CodeIgniter
I have tried with below code
Controller
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
}
}
View
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo $d->invoice_id;
?>
</body>
</html>
But data is not printing in the view.How can I print the values??

You Can't foreach and pass the data to view.
public function getdata()
{
$result = $this->Mdi_download_invoices->download_pdf_files(12);
$data['d'] = $result;
$this->load->view('download_all_invoices/pdf',$data);
}
Note: Since you're using echo $d->invoice_id; check whether your result object (row, result)

I think you are looking for this :
<?php
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
$this->load->view('download_all_invoices/pdf',$d);
}
}
?>

Related

How to display data from json url using php decode?

I am not able to display data from this url using php json decode:
https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it
here is the data provider:
https://mymemory.translated.net/doc/spec.php
thanks.
What I want is to setup a form to submit words and get translation back from their API.
here is my code sample:
<?php
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
// parse the JSON
$data = json_decode($json);
// show the translation
echo $data;
?>
My guess is that you might likely want to write some for loops with if statements to display your data as you wish:
Test
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
if (isset($data["responseData"])) {
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html = $value;
} else {
continue;
}
}
} else {
echo "Something is not right!";
}
echo $html;
Output
Ciao Mondo!
<?php
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
';
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html .= '<p>' . $value . '</p>';
} else {
continue;
}
}
$html .= '
</body>
</html>';
echo $html;
?>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
<p>Ciao Mondo!</p>
</body>
After many researches I got it working this way:
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Map&langpair=en|it');
$obj = json_decode($json);
echo $obj->responseData->translatedText;
thank you all.

Fetch and decode JSON from api.coinmarketcap.com

How can I get variables "price_usd" for bitcoin & ethereum from JSON url https://api.coinmarketcap.com/v1/ticker
This works:
$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
$lastPrice = $json[0]["price_usd"];
echo $lastPrice;
However, I would like to do something like this:
<?php
$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
function price($ticker) {
foreach($json[] as $item) {
if($item->id == $ticker) {
echo $item->price_usd;
}
}
}?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo price("bitcoin");?>
<?php echo price("etheruem");?>
</body>
</html>
You can use array_column for this:
$json = json_decode($fgc, TRUE);
// following line will create assoc array as key => value for 'price_usd' as key and 'id' as value
$js = array_column($json, 'price_usd', 'id');
echo $js["bitcoin"];
General Function:
$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);
function price($curr) {
global $decoded_json;
$js = array_column($decoded_json, 'price_usd', 'id');
return $js[$curr];
}
echo price("bitcoin");
echo price("ethereum");
Another solution without global var:
// this will create a new request to api.coinmarketcap.com on each call
function price($curr) {
$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);
$js = array_column($decoded_json, 'price_usd', 'id');
return $js[$curr];
}
Now that the question is updated, you can just cast the $js to object and use it like an object:
$js = (object) $js;
echo $js->bitcoin;

PHP Language Editor, Array Keys

I have found the script.
http://www.aota.net/forums/showthread.php?t=24155
My lang.php
<?php
$Lang = array(
'TEXT' => "baer",
'GRET' => "hallo",
'FACE' => "face",
'HAPY' => "happy",
'TOOL' => "tool",
);
My edit.php
<?
// edit the values of an array ($Lang["key"] = "value";) in the file below
$array_file = "lang.php";
// if POSTed, save file
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
unset($_POST['submit']); // remove the submit button from the name/value pairs
$new_array = ""; // initialize the new array string (file contents)
$is_post = true; // set flag for use below
// add each form key/value pair to the file
foreach (array_keys($_POST) as $key)
{ $new_array .= "\$Lang[\'$key\'] => \"".trim($_POST[$key])."\",\n"; }
// write over the original file, and write a backup copy with the date/time
write_file($array_file, $new_array);
write_file($array_file . date("_Y-m-d_h-ia"), $new_array);
}
// write a file
function write_file($filename, $contents)
{
if (! ($file = fopen($filename, 'w'))) { die("could not open $filename for writing"); }
if (! (fwrite($file, $contents))) { die("could not write to $filename"); }
fclose($file);
}
// read the array into $Lang[]
$file_lines = file($array_file);
$Lang = array();
foreach ($file_lines as $line)
{
list($b4_key, $key, $b4_value, $value) = explode('"', $line);
if (preg_match("/Lang/", $b4_key))
{ $Lang[$key] = $value; }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Language Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1><?= $array_file ?></h1>
<? if (!isset($is_post)) { ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<? } ?>
<table>
<?
// loop through the $Lang array and display the Lang value (if POSTed) or a form element
foreach ($Lang as $key => $value)
{
echo "<tr><td>$key</td><td>";
echo isset($is_post) ? "= \"$value\"": "<input type=\"text\" name=\"$key\" value=\"$value\">";
echo "</td></tr>\n";
}
?>
</table>
<? if (!isset($is_post)) { ?>
<p><input type="submit" name="submit" value="Save"></p>
</form>
<? } ?>
</body>
</html>
Unfortunately I can not read array and Keys from lang.php.
Script writer, writes:
all lines in array.txt did do set $ Bid [] will be lost.
But I want lang.php after the change save as a PHP file that would go?
I want to create a drop-down list and load array with matching keys, change key text and save.
I thank you in advance for your help!
You shouldn't read lang.php file.
You should include it.
Better way:
require_once('lang.php'); // or require_once($array_file);
and remove these lines:
// read the array into $Lang[]
$file_lines = file($array_file);
$Lang = array();
foreach ($file_lines as $line)
{
list($b4_key, $key, $b4_value, $value) = explode('"', $line);
if (preg_match("/Lang/", $b4_key))
{ $Lang[$key] = $value; }
}
# # # # # # # #
As I understand your file contents only one language, doesn't it?
If no, will be a little modifications in the code.
<?
// edit the values of an array ($Lang["key"] = "value";) in the file below
$array_file = "lang.php";
// if POSTed, save file
if (isset($_POST['submit'])) {
unset($_POST['submit']); // remove the submit button from the name/value pairs
$is_post = true; // set flag for use below
// write over the original file, and write a backup copy with the date/time
write_file($array_file, $new_array);
write_file($array_file . date("_Y-m-d_h-ia"), $new_array);
file_put_contents($array_file, serialize(array(
'timestamp' => time(), // after you can display this value in your preffered format
'data' => serialize($_POST)
)));
}
$Lang_content = #unserialize(#file_get_contents($array_file));
if (!array_key_exists('data', $Lang_content)) {
$Lang_content = array(
'timestamp' => 0, // or time()
'data' => serialize(array())
);
}
$Lang_template = array( // If you want
'TEXT' => "baer",
'GRET' => "hallo",
'FACE' => "face",
'HAPY' => "happy",
'TOOL' => "tool",
);
$Lang = array_merge(
$Lang_template,
unserialize($Lang_content['data'])
);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Language Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1><?= $array_file ?></h1>
<? if (!isset($is_post)) { ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<? } ?>
<table>
<?
// loop through the $Lang array and display the Lang value (if POSTed) or a form element
foreach ($Lang as $key => $value) {
echo "<tr><td>$key</td><td>";
echo isset($is_post) ? "= \"$value\"" : "<input type=\"text\" name=\"$key\" value=\"$value\">";
echo "</td></tr>\n";
}
?>
</table>
<? if (!isset($is_post)) { ?>
<p><input type="submit" name="submit" value="Save"></p>
</form>
<? } ?>
</body>
</html>

Undefined variable in CodeIgniter View

I'm trying to print my key/value pairs of data in my CodeIgniter view. However, I'm getting the following error. What I'm I doing wrong?
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/search_page2.php
Line Number: 8
application/controller/search.php
// ...
$this->load->library('/twitter/TwitterAPIExchange', $settings);
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=johndoe';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$this->load->view('search_page2', $data);
// ...
application/views/search_page2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Twitter Test</title>
</head>
<body>
<?php print_r($data); ?>
<?php foreach ($data as $key => $value): ?>
<h2><?php echo $key . ' ' . $value . '<br />'; ?></h2>
<?php endforeach ?>
</body>
</html>
to get the data array accessible in the view do like
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$data['data'] = $data;
$this->load->view('search_page2', $data);
else only the variables with names as its keys will be available in the view not the data variable we pass.
update:
this is in response to your comment to juan's answer
Actually if you are trying make it working in the other way proposed.
controller code will be having no change from the code you posted.
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$this->load->view('search_page2', $data);
but in the view code you will need to just do.
<h2>url <?PHP echo $url; ?><br /></h2>
<h2>getfield <?PHP echo $getfield; ?><br /></h2>
<h2>requestMethod <?PHP echo $requestMethod; ?><br /></h2>
instead of the foreach loop as your keys in $data are already available as respective named variables inside the view.
The variables to use in your template are
$url, $getfield, $requestMethod
$data is the container for the variables that are passed to the view and not accessible directly
If you do need $data accessible to the view, use a different wrapper object
$container = array();
$container ['url'] = $url;
$container ['getfield'] = $getfield;
$container ['requestMethod'] = $requestMethod;
$container ['data'] = $data;
$this->load->view('search_page2', $container);

My codes cannot extract the XPath correctly in PHP

I wrote some codes in PHP to extract content of some elements from other websites. These elements are addressed by XPath. These codes worked for one website successfully but failed for the other one. Therefore, I am sure that not the whole code is incorrect.
by the way: I extracted the element's XPath address by using 'Inspect Element' in Firefox and Right Click on the element and choosing 'Copy XPath'.
What is wrong for the second website?
thanks
Here is the code:
//MyCode.PHP
<html>
<head>
<title>This is the title</title>
</head>
<body>
<?php
class EmDIV
{
public $url="";
public $content="";
public $name="";
public $query="";
public function EmDIV($CdivName,$Curl,$CQuery)
{
$this->name=$CdivName;
$this->url=$Curl;
$this->query=$CQuery;
$html = new DOMDocument();
#$html->loadHtmlFile($this->url);
$bodies = $html->getElementsByTagName('body');
assert($bodies->length === 1);
$body = $bodies->item(0);
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query($this->query);
//echo #$body->saveHTML();
if($nodelist->length==1)
{
$this->content=$nodelist->item(0)->textContent;
//sanitizing
//$this->content=Jsoup.clean($this->content, Whitelist.basic());
}
//echo $nodelist->item(0)->nodeName;
foreach ($nodelist as $node)
echo $node->getNodePath()."\n";
}
}
$emdiv=array(
//new EmDIV('parsmalaysia','http://www.parsmalaysia.com/exchange.html','/html/body/div/div[5]/div/div/div/div/div/div/div/div/div/div/table/tbody/tr/td[4]/text()'),
new EmDIV('atlas-exchange','http://atlas-exchange.com/','/html/body/div/div/table/tr/td/table/tr/td/div/div[10]/div/div/div/table/tr[3]/td[2]/text()'),
new EmDIV('usunmalaysia','http://www.usunmalaysia.com/Home.aspx','/html/body/form/table/tbody/tr[3]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[4]/td/table/tbody/tr/td/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[3]/td/table/tbody/tr[4]/td[2]/text()'),
);
?>
<table border="1">
<tr>
<td>Site</td>
<td>RM Price</td>
</tr>
<?php
foreach ($emdiv as $ed)
{
echo "<tr>";
echo "<td>".$ed->name."</td>";
echo "<td>".$ed->content."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
In the second page there are no tbody elements. You have to remove all tbody elementes from the path. Firefox show the tbody elements because they are part of the internal structure of the tables, but they are not in the markup you are retrieving.

Categories