parse json with php 5 not working - php

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.

Related

How to get the values from JSON Array Stored as Value in JSON using PHP?

`{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}`
I am trying to get the value of rno using PHP code
`$data = json_decode($json, true);
foreach ($data as $item) {
$name = $item['name'] ;
$number= $item['rno'] ;
}`
#Sahil Gulati's code is more prefect and right way to parse the json in php
here is an other way to parse the json data in php
<?php
$data = json_decode($json, true);
foreach ($data as $item) {
foreach ($item as $val) {
echo $name = $val['name'];
echo $number = $val['rno'];
}
}
?>
the above code that i have shared you can understand easily. but after learning that how to parse json data in php you should use #Sahil Gulati's mathod.
Change this to:
foreach ($data as $item)
This:
foreach ($data["student"] as $item)
Try code snippet here
PHP code:
<?php
ini_set('display_errors', 1);
$data = json_decode($json, true);
foreach ($data["student"] as $item)
{
$name = $item['name'];
$number = $item['rno'];
}
You should take a closer look at the structure of the json encoded data. That helps to implement a clean iteration:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
$output = [];
array_walk($data->student, function($entry) use (&$output) {
$output[] = $entry->rno;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => 187654
)
The output format has been chosen as an array, since the json structure suggests that multiple students can be contained.
If you are only directly interested in the rno property of the first entry in the student array, then you can access it directly:
<?php
$input = <<<JSON
{
"student": [{
"name": "Alice",
"rno": "187654"
}]
}
JSON;
$data = json_decode($input);
var_dump($data->student[0]->rno);
The output of that variant obviously is:
string(6) "187654"

PHP load json data, output is empty

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;

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

How to get String value from json_decode in php

My json-data is as follows -
[{"name": "ram"}]
What I want is the value of name in a variable e.g., $fname. I have tried -
<?php
$jsondata = '[{"name": "ram"}]';
//$obj = json_decode($jsondata);
$obj = json_decode($jsondata,true);
print_r($obj); // This line outputs as :- Array ( [0] => Array ( [name] => ram ) )
//What I need is value of key
print_r($obj['name']);
foreach ($obj as $k=>$v){
echo $v;
}
?>
But I am unable to get desired output.
Here how to get that value
<?php
$jsondata = '[{"name": "ram"}]';
$obj = json_decode($jsondata,true);
//In case have multiple array
foreach ($obj as $k){
echo $k['name'];
}
//else
$obj[0]['name'];
//if
$jsondata = '{"name": "ram"}';
$obj = json_decode($jsondata,true);
//use
echo $obj['name'];
?>
As your output indicates, your JSON string represents an array containing one object. As you know that you want a value contained within the first element, you can get it directly:
$jsondata = '[{"name": "ram"}]';
$obj = json_decode($jsondata, true);
$name = $obj[0]['name'];
echo $name;

How to get values of a json array in php?

I have json like this:
{
"Products": [
{
"_id": 1
....
},
{
"_id": 2
....
}
]
}
And got this json :
$str = file_get_contents($_FILES["uploadFile"]["tmp_name"]);
// convert object => json
$json = json_encode($str);
// convert json => object
$decoded = json_decode($json,true);
Now i want to see all _id of Producs.
I use this echo $decoded[0]['_id']; but it shows nothing.
Any ideas?
$decoded = json_decode($json, true);
echo $decoded['products'][0]['_id'];
This decodes the json as an array that you can use just like any other array in PHP, if you have trouble accessing values, then simply do a print_r($decoded) and that should show you its structure
If you want to loop over all the ids, then simply do a foreach loop
foreach($decoded as $inner_array) {
foreach($inner_array as $products) {
echo $products['_id'];
}
}
Working demo
You should be aware of using quotes on your json string :)
keys and values .
You don't need to encode it. the string is already in json format
$str= '{"Products": [{"_id": "1"},{"_id": "2"}]}';
$decoded = json_decode($str,true);
echo $decoded['Products'][0]['_id'];

Categories