PHP load json data, output is empty - php

I try to load data from my JSON file into php see my code below
JSON:
{
"drinks":[
"1" {"coffee": "zwart", "country":"afrika"},
"2" {"tea": "thee", "country":"china"},
"3" {"water": "water", "country":"netherlands"},
]
}
PHP:
<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0][coffee];
echo $drinks;
?>
If I run this code my output is empty. Who can help me in the right direction?

Your JSON input is NOT valid according to RFC 4627 (JSON specification). So the correct json string must be:
{"drinks":[
{"coffee": "zwart", "country":"afrika"},
{"tea": "thee", "country":"china"},
{"water": "water", "country":"netherlands"}
]
}
so your code would work:
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0]['coffee'];
echo $drinks;
Or at least, you must format your json string like below:
{
"drinks":[
{
"1": {"coffee": "zwart", "country":"afrika"},
"2": {"tea": "thee", "country":"china"},
"3": {"water": "water", "country":"netherlands"}
}
]
}
And you can get your data in this way:
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0]['1']['coffee'];
echo $drinks;

Related

PHP: Unable to echo values from nested Array in PHP

I want to echo data which is in JSON format. I converted from JSON to PHP array using json_decode() but it is not getting echoed. Blow is my code:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->extract;
?>
I only needed extract data which contains information for that title.
If you run the request in the browser, you will see that the returned JSON does not contain a pageids property, but is of the form
{
"batchcomplete": "",
"query": {
"normalized": [
...
],
"pages": {
...
}
}
}
If all you want is to grap the extract from the first item, you could do:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$page = reset($data->query->pages);
$extract = $page ? $page->extract : null;

parse json with php 5 not working

I am trying to parse and list a json file. I have it as Unicode-8 without BOM. File is operational. Structure:
// "games.json" :
// {"data":[
// {"game":"5359","Date":"07/08/2015"},
// {"game":"5355","Date":"10/20/2007"},
....
<?php
// copy file content into a string var
$jsondata = file_get_contents("games.json");
// convert the string to a json object
$json = json_decode($jsondata,true);
var_dump($json); // DW!
foreach($json["data"] as $data_X)
{echo $data_X->game;}
?>
Why doesn't this work?
<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
use $json = json_decode($jsondata); instead of `$json = json_decode($jsondata,true); True parameter convert it into array not json object.

Get JSON from URL by PHP

I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);

Importing JSON file to PHP [error Trying to get property of non-object]

I tried import one JSON file to PHP and use it, but the server return: "Trying to get property of non-object".
If I put manually the text in JSON file into a PHP file the server return correctly
index.php
<?php
if (isset($_GET['dir'])) {
$dir = $_GET['dir'];
$dir = $dir . "/";
} else {
$dir = "";
}
$about_dir = $dir . "about.json";
//1st try
$json_data = file_get_contents($about_dir);
$json_a = json_decode($json_data, true);
echo $json_a['T'];
//2nd try
$json = json_decode($json_data, true);
print $json->{"T"};
//3th try
$json = '{"T": "Test","About": "About T"}';
$obj = json_decode($json);
print $obj->{'About'};
return $about_dir;
?>
about.json
[
{
"T": "Test",
"About": "About T"
}
]
What is wrong? I tried follow this example ( http://php.net/manual/en/function.json-encode.php ). Also, I searched here in stackoverflow, but I never use JSON.
Someone can help me?
Thank you.
You have to access object elements by using arrow and array elements by using square bracket. It's an array so you have to use square bracket here.
I use a method similar to this to convert JSON to PHP
function json2object($json){
$json_array = json_decode($json, true);
foreach($json_array as $k=>$v){
$this->{$k}=$v;
}
}
So in your case you could use something like :
$json_a = json_decode($json_data, true);
foreach($json_a as $k=>$v){
$obj->{$k}=$v;
}
Hope this works as well for you as it does for me.
$json = '[
{
"T": "Test",
"About": "About T"
}
]';
$obj = json_decode($json);
//print $obj->{'About'};
//print_r($obj);
foreach($obj as $value)
{
echo $value->T;
echo $value->About;
}
I try, but seems that the error is in get_contents.
If I use this code:
$json = '{"T": "Test","About": "About T"}';
$obj = json_decode($json);
var_dump(json_decode($json));
The return is:
About T object(stdClass)#3 (2) { ["T"]=> string(4) "Test" ["About"]=> string(7) "About T" }
If I import the contents:
$json = file_get_contents($about_dir);
//$json = '{"T": "Test","About": "About T"}';
$obj = json_decode($json);
var_dump(json_decode($json));
And write in about.json this line: {"T": "Test","About": "About T"}
The return is:
NULL

How to add attribute in JSON in PHP?

I have Json in PHP like this:
$json = '{"total":"100", "page":"1", "records":"100", "rows": [
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';
and I want to add
"test1":"5","test2":"7"
into JSON above.
so it will be like this:
$json = '{"total":"100", "page":"1", "records":"100", "rows": [
{"no":"1","part_number":"2","part_name":"3","price":"4","test1":"5","test2":"7","note":"8"}]}';
Please, help me. How to add attribute in JSON in PHP?
$json = '{"total":"100", "page":"1", "records":"100", "rows": [
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';
// decode json
$json = json_decode($json);
// add data
$json->rows[0]->test1 = "5";
$json->rows[0]->test2 = "7";
// echo it for testing puproses
print_r($json);
// re-encode
$json = json_encode($json);
echo $json;

Categories