Undefined variable in CodeIgniter View - php

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);

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.

How to pass values from foreach to view in codeigniter

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);
}
}
?>

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;

Error Parsing Google Book JSON API with PHP

I am stuck now, I tried to parse JSON API Google Book using PHP.
this is my PHP
<?php
$api = 'AIzaSyB2__dPng5IGT9Nlca0UT7FxN459mrITmo';
$book_api = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=fift+shades+of+grey&key='.$api);
$book = json_decode($book_api);
$a = $book->items;
$results = $a->volumeInfo;
$images = $results->imageLinks;
foreach ($results as $result) {
$title = $result->title;
$author = $result->authors;
$desc = $result->description;
$cat = $result->categories;
$pages = $result->pageCount;
}
foreach ($images as $image) {
$thumb = $image->thumbnail;
}
?>
<html>
<head>
<title>Exampe API Google Book</title>
</head>
<body>
<h1><?php echo $title; ?></h1><br/>
<?php echo $desc; ?>
</body>
</html>
I get error
Notice: Trying to get property of non-object in
and
Warning: Invalid argument supplied for foreach() in
I want to use to display the search results book.
Can you help me to fix it?
Thanks
You were not selecting the right property of array. I have given a complete solution for your reference below. You really don't need two loops for it.
<?php
$api = 'AIzaSyB2__dPng5IGT9Nlca0UT7FxN459mrITmo';
$book_api = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=fift+shades+of+grey&key='.$api);
$book = json_decode($book_api);
$meta_data = $book->items;
?>
<html>
<head>
<title>Exampe API Google Book</title>
</head>
<body>
<?php
for($i = 0; $i < count($meta_data); $i++)
{
$title = $meta_data[$i]->volumeInfo->title;
$author = $meta_data[$i]->volumeInfo->authors;
$desc = $meta_data[$i]->volumeInfo->description;
$cat = #$meta_data[$i]->volumeInfo->categories;
$pages = #$meta_data[$i]->volumeInfo->pageCount;
$thumb = $meta_data[$i]->volumeInfo->imageLinks->thumbnail;
echo "<h1>$title</h1><br/>";
echo "<p><img src=\"$thumb\" style=\"float:left; padding: 10px;\">$desc</p><br clear=\"all\" /><hr />";
}
?>
</body>
</html>
If you look at your resulting json -
...
items": [
{
"kind": "books#volume",
"id": "V1Re
...
This $a = $book->items; returns an array.
So doing this is wrong -
$results = $a->volumeInfo;
You need to iterate through $a using a foreach and get each individual volumeInfo and modify the rest of your code accordingly

calling a function with require but variables and arrays are undefined

Why aren't my variable seen when called with require ?
function.php
<?php
function paginator(){
$links = array("index.php", "services.php", "content.php","contact_us.php" );
$trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
foreach ($links as $key => $value) {
if ($value == $trimslug ) {
$GLOBALS['$page'] = $key;
}
}
$page = $GLOBALS['$page'];
$next = $page+1;
$previous = $page-1;
}
?>
content.php
<?php
session_start();
require './functions.php';
paginator();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pagination</title>
</head>
<body>
<h2>Now on Page : <?php echo $page?></h2>
<a href="<?php echo $links[$next] ?>" >Next</a>
<br><br><br>
<a href="<?php echo $links[$previous]?>" >Previous</a>
<br>
</body>
</html>
I would like to be able to see my variables, when using the require function as this piece of code will be on every page. This might be a very noobish concept to grasp but I would really like someone to illustrate the concept properly.
This seemed to work, Thank you everyone.
<?php
$links = array("index.php", "services.php", "content.php","contact_us.php" );
$trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
$page = null;
function paginator(){
global $links,$trimslug,$next,$previous,$page;
foreach ($links as $key => $value) {
if ($value == $trimslug ) {
// $GLOBALS['$page'] = $key;
$page = $key;
}
}
$next = $page+1;
$previous = $page-1;
}
?>
The variables inside paginator are only in the scope of the function, not the php file. If you want to access them outside that function, just move those variables outside of it. Eg
$page=null;
$links=...
function paginator(){
...
}
This is because the variables are defined in the scope of the function paginator();
If you want them to be accesible in the scope of content.php, either declare them like this:
global $variable = 'value';
Or, just declare them in function.php without the need of the function & it's subsequent call in content.php.
Variables in PHP are limited to the scope of the function, unless called via an argument or by adding to the global array.
Global arrays are bad practice, just sayin.
You could always make the variables into a private class and call it as needed, though that's pretty tricky for beginners.

Categories