JSON parse URL with PHP JSON decode - php

I have JSON data:
{"took":3,
"timed_out":false,
"_shards":{ "total":5,
"successful":5,
"failed":0
},
"hits":{"total":105,
"max_score":1.0,
"hits":[
{"_index":"csv",
"_type":"logs",
"_id":"AVeyr-BQodQ9UhW1sdW0",
"_score":1.0,
"_source":{"message":"james,wonder\r",
"#version":"1",
"#timestamp":"2016-10-11T07:40:52.332Z",
"path":"D:\\logstash-2.4.0\\bin\\Book1.csv",
"host":"CHNL-LT-544",
"fname":"fa1368a93aa39b2346329c1734be1f4b",
"lname":"wonder"
}
},
{"_index":"csv",
"_type":"logs",
"_id":"AVeyr-BQodQ9UhW1sdW1",
"_score":1.0,
"_source":{"message":"muskaan, wonder\r",
"#version":"1",
"#timestamp":"2016-10-11T07:40:52.332Z",
"path":"D:\\logstash-2.4.0\\bin\\Book1.csv",
"host":"CHNL-LT-544",
"fname":"479085e94d305129527fa80978613e95",
"lname":"wonder"}
},
{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdW3","_score":1.0,"_source":{"message":"altimetrik,india\r","#version":"1","#timestamp":"2016-10-11T07:40:52.333Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"8b3ecf275832c79b36d62d74f47257c9","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdW8","_score":1.0,"_source":{"message":"kool,indiae\r","#version":"1","#timestamp":"2016-10-11T07:40:52.335Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"d2edbdce885720c70f38f36748c37600","lname":"indiae"}},{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdXA","_score":1.0,"_source":{"message":"ds,dssd\r","#version":"1","#timestamp":"2016-10-11T07:40:52.336Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"91594a75bc6bfb0ec800d4f454e1fe87","lname":"dssd"}},{"_index":"csv","_type":"logs","_id":"AVeytJ0iodQ9UhW1sdXf","_score":1.0,"_source":{"message":"kool,india\r","#version":"1","#timestamp":"2016-10-11T07:46:02.839Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"d2edbdce885720c70f38f36748c37600","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytJ0iodQ9UhW1sdXi","_score":1.0,"_source":{"message":"karnataka,india\r","#version":"1","#timestamp":"2016-10-11T07:46:02.840Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"2a0785caed6bfd2ffb6ad5a449f2bd0e","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdXq","_score":1.0,"_source":{"message":"james,wonder\r","#version":"1","#timestamp":"2016-10-11T07:48:39.550Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"fa1368a93aa39b2346329c1734be1f4b","lname":"wonder"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdX0","_score":1.0,"_source":{"message":"rajasthan,india\r","#version":"1","#timestamp":"2016-10-11T07:48:39.558Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"449b07d9038569b2d69243dadfae0371","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdX5","_score":1.0,"_source":{"message":"najeeb,shariff\r","#version":"1","#timestamp":"2016-10-11T07:48:39.573Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"be7a5e98258338fa63086f44e8bd1850","lname":"shariff"}}]}}
I want to print only 2 fields from this JSON; fname and lname. Please tell me how I can achieve this using PHP.
$url = 'localhost:9200/csv/_search';;
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['hits'] as $item) {
print $item['fname'];
}
But getting error Undefined index

$url = 'localhost:9200/csv/_search';;
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['hits']['hits'] as $item) {
echo "<p>{$item['_source']['fname']}</p>";
echo "<p>{$item['_source']['lname']}</p>";
}
Array path of fname and lname goes like [hits][hits][0][_source][fname] and [hits][hits][0][_source][lname]. [hits][hits] should be iterated in the loop to access each _source element.
As RiggsFolly said, you need to do print_r($json) to see how the array is structured especially when you encounter nested arrays.
Hope it helps!

Related

Retrieve videoId From JSON Using PHP

Link To JSON File: https://pastebin.com/gXcnNnUK
Code I've Tried So Far:
$json = json_decode($json, true);
foreach($json as $data){
echo $data['videoId'];
}
But it's not returning values. Is there any better approach to do it?
On line 3, did you mean to iterate over $arr instead of $json?
$json = file_get_contents('json.json');
$arr = json_decode($json, true);
foreach($arr['contents']['sectionListRenderer']['contents']['2']['itemSectionRenderer']['contents'] as $pero){
$video_id_list .= $pero['compactVideoRenderer']['videoId'].',';
}

PHP JSON multiple echo value

In addition to the question yesterday: Question
I got multiple (3) Items in the json file:
results.json
["{\"Produkt\":{\"Produktkategorie\":\"Artikel1\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante1\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel2\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante2\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel3\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante3\"}}}"]
I want echo all three value from "Produktkategorie" and the value "MaxBreite"
It should look like this:
Artikel1 - 250
Artikel2 - 250
Artikel3 - 250
My code looks like this:
$json = file_get_contents('results.json');
$json = json_decode($json, true);
$anzahl = count($json) -1;
$anzahlstart = 0;
while ($anzahlstart < $anzahl) {
$json = json_decode($json[$anzahlstart], true);
$ProduktkategorieFile = $json['Produkt']['Produktkategorie'];
$MaxBreiteFile = $json['Produkt']['Optionen']['MaxBreite'];
echo $ProduktkategorieFile. "-" .$MaxBreiteFile;
$anzahlstart ++;
}
Unfortunately my Code throws a error after passing first line:
Notice: Undefined offset: 1 in
After that I don't get any result.
Kings of coding, could you help me again please :)
Do you need like this?:-
<?php
$json_string = file_get_contents('results.json');
$json = json_decode($json_string, true);
// I hope the above line gives you exact json what you shown to us
foreach ($json as $jso){
$array = json_decode($jso, true);
echo $array['Produkt']['Produktkategorie'].' - '.$array['Produkt']['Optionen']['MaxBreite'];
echo PHP_EOL;
}
Output:-https://eval.in/728430
Note:- If yes then I hope you are able to get other values easily.Thanks
The problem is with the $json variable name: You're reassigning it on this line: $json = json_decode($json[$anzahlstart], true);
Rename this variable and you're good to go!
I would also replace the while loop with a foreach loop as shown in my example:
<?php
//With foreach
$original = '["{\"Produkt\":{\"Produktkategorie\":\"Artikel1\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante1\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel2\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante2\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel3\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante3\"}}}"]';
$decoded = json_decode($original);
foreach($decoded as $encodedProduct){
$product = json_decode($encodedProduct,true)['Produkt'];
echo $product['Produktkategorie'] . " - " . $product['Optionen']['MaxBreite'] . "\n";
}
//Original fixed code
$json = json_decode($original, true);
$anzahl = count($json);
$anzahlstart = 0;
while ($anzahlstart < $anzahl) {
$decodedJson = json_decode($json[$anzahlstart], true);
$ProduktkategorieFile = $decodedJson['Produkt']['Produktkategorie'];
$MaxBreiteFile = $decodedJson['Produkt']['Optionen']['MaxBreite'];
echo $ProduktkategorieFile. " - " .$MaxBreiteFile . "\n";
$anzahlstart ++;
}
Your problem is, that you are trying to decode an array of json string, instead of the string itself.
so that would be like this now.
$json = file_get_contents('results.json');
$json = json_decode($json[0], true); // notice [0];on this line.
...
After reading the other question, I have had this problem before, but you essentially need to do two things. in your ajax.
$.ajax({
...
data : JSON.stringify(data)
})
This changes an object into a json string,
Then on your server you do the decode.
something like this
$json = json_decode($jsonstringGoesHERE , true);
For more information in understanding the issue, have a look at this other post.
jQuery ajax, how to send JSON instead of QueryString

PHP Cannot loop through nested JSON

I have an API which is returning some nested JSON data with multiple levels. My PHP code to loop through is below but I'm not getting any output:
$data = json_decode($output, true);
foreach($data as $item){
$title = $item->events->name->text;
echo $title;
}
An example of the data can be found here: http://i.imgur.com/Y55vl7n.png
I am trying to print the text name of each of the events (events->name->text)
There is a problem in your code, when you decode the json string, you use:
$data = json_decode($output, true);
It is converting everything to "array" (http://php.net/manual/en/function.json-decode.php), so you cannot access it like if they were objects.
You have to do:
foreach($data as $item){
$title = $item["events"]["name"]["text"];
echo $title;
}
Hope this helps!

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'];

How can I display JSON data using PHP

I have already created a dynamic JSON file.
My code is:
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro)) {
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
How can I get data from the JSON file? Using a while loop or anything similar?
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($res))
{
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
First, you have mistake on line 2
mysql_fetch_array($res)
AND NOT
mysql_fetch_array($respro)
Second, Use file_get_contents and json_decode functions
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
Thanks
This is how you see the posted json data in your php file.
I would prefer that:
$json_string=json_encode($records);
you must put the header
header('Content-Type: application/json;charset=utf-8');
and other side
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
First of all the way you are writing to the file inside the while loop is wrong.. Because you are unneccesarily calling the file_put_contents() again and again which is simply degrading your code performance..
So rewrite your code to this..
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro))
{
$records[]= $rowpro;
}
file_put_contents("product_file.json",json_encode($records));
To read the JSON data , make use of file_get_contents()
Like this..
$jsonData = file_get_contents("product_file.json");
echo $jsonData; //<--- Prints your JSON
In PHP ,
header('Content-Type: application/json;charset=utf-8');
$str = file_get_contents('product_file.json');
$jsonData = json_decode($str, true); //json decode
And in jquery you can use jQuery.getJSON example ,
$.getJSON( "product_file.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

Categories