How to parse json array using php foreach? - php

I want to get id,url,img and title of videos in the JSON data.My current code doesn't output anything
could any one tell me what i am doing wrong.Thanks
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2, true);
$i = 0;
foreach($data->videos as $values)
{
echo $values->id . "\n";
echo $values->url . "\n";
echo $values->img . "\n";
echo $values->title . "\n";
$i++;
}
data:
{
"cat": {
"id": "1234567",
"source_id": null,
"title_en": "first season",
"description_en": "This is spring category ",
},
"videos": [{
"id": "312412343",
"url": "\/2015-07-17\/1abcd.mp4",
"img": "image\/44\/\/2015-07-17\/1abcd.jpg",
"title": "first",
}, {
"id": "2342343",
"url": "\/2015-07-16\/2dcdeg.mp4",
"img": "images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title": "second",
}];
}
validated json data:
{
"cat":{
"id":"1234567",
"source_id":null,
"title_en":"first season",
"description_en":"This is spring category "
},
"videos":[
{
"id":"312412343",
"url":"\/2015-07-17\/1abcd.mp4",
"img":"image\/44\/\/2015-07-17\/1abcd.jpg",
"title":"first"
},
{
"id":"2342343",
"url":"\/2015-07-16\/2dcdeg.mp4",
"img":"images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title":"second"
}
]
}

Because you call
$data = json_decode($code2, true);
your $data is an array and not an object as you try to access it. So either access it as regular array, or change 2nd argument of json_decode() to false (or removeit as this is default), as this is what controls conversion behavior.
See docs: http://php.net/manual/en/function.json-decode.php
Your data is not a valid JSON (; at the end, redundant and missing comas - it's simply broken).
In case of such problems, var_dump() is pretty helpful to inspect what data you are really working with.

Related

Generate dynamic html with JSON output (with php)

I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:

How to access multi-level json tree in PHP for database insertion

I am accessing an API where the JSON data is returned as below.
{
"name": "",
"count": 4,
"frequency": "",
"version": 3,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "",
"results": {
"collection": [{
"textlink": {
"href": "http://text1.com",
"text": "Text 1"
},
"index": 1,
"url": ""
}, {
"textlink": {
"href": "http://text2.com",
"text": "Text 2"
},
"index": 2,
"url": ""
}, {
"textlink": {
"href": "http://text3.com",
"text": "Text 3"
},
"index": 3,
"url": ""
}, {
"textlink": {
"href": "http://text4.com",
"text": "Text 4"
},
"index": 4,
"url": ""
}]
}}
As you can see the JSON tree returned has multi-step levels. I am wanting to be able to take some of the deeper levels, in PHP, and insert into a database.
Currently I am using this code to try and echo the data (once I am able to I can then work on inserting it to a database no problem)
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);
foreach($results as $item) {
echo $item->results[0]->collection[0]->textlink[0]->href;
echo "<br>";
echo $item->results->collection['href'];
echo "<br>";
echo $item->results->collection['text'];
}
?>
As you can see above I have tried several ways to access the deeper levels f data that are being displayed but with no avail.
I am currently getting errors of 'trying to get property of a non-object'. How is it possible to reach the data in this array?
try:
echo $results['results']['collection'][0]['textlink']['href'];
$obj = json_decode( $json, true ); foreach ( $obj['key'] as $key => $value ) { echo $value; }
foreach ($response['results']['collection'] as $textlink) {
$row = $textlink['textlink'];
echo $row['href'];
echo "<br>";
echo $row['text'];
echo "<br>";
}
you can do foreach like this, which loops only items in collection
I would suggest to do something like this (According to me, correct way to fetch results from API responses):
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$response = json_decode($response);
foreach($response->results->collection as $item) {
echo $item->textlink->href;
echo "<br>";
echo $item->textlink->text;
echo "<br>";
echo $item->index;
echo "<br>";
echo $item->url;
}
?>

Loop through JSON with php, and write to it. Output is null

My goal is to loop through each Item within the JSON and add an additional key called "modal" to each "Item", and the value paired with that key that would contain html. I stripped down my code below.
I'm able to add 'modal' to each 'Item', however the value somehow gets set to null, instead of the html I would like it to be.
JSON file:
{"Item":{
"thumbnail":"http://...",
"title": "Item title"
},
"Item":{
"thumbnail":"http://...",
"title": "Item title"
}}
php:
$json_a=json_decode($json, true);
foreach ($json_a['Item'] as &$obj){
$out = '<img src=\"' . $obj['thumbnail'] . '\">';
$out .= '<span>' . $obj['title'] . '</span>';
$obj['modal'] = $out; //value of $out doesn't get passed in, instead the value becomes null.
}
$json_a=json_encode($json_a);
print_r($json_a);
json output:
...{'modal': null}...
Edited the JSON to be valid. It comes from Amazon's product API, I shortened it for this example and made it invalid.
Your JSON is invalid. It is an object with duplicate keys ("Item"). You should use an array instead:
[
{
"thumbnail": "...",
"title": "..."
},
{
"thumbnail": "...",
"title": "..."
}
]
Then you can iterate over it and add 'modal' to all elements:
$json_a = json_decode($json, true);
foreach ($json_a as &$obj) {
$out = '<img src=\"' . $obj['thumbnail'] . '\">';
$out .= '<span>' . $obj['title'] . '</span>';
$obj['modal'] = $out;
}
$json_a = json_encode($json_a);
print_r($json_a);
Its simple your json is not valid
{
"Item": {
"thumbnail": "http://...",
"title": "Item title",
^---- This should not be here
},
"Item": {
^-------------- Duplicate name
"thumbnail": "http://...",
"title": "Item title",
^---- This should not be here
}
}
The main issue is that you need to generate your object or array properly using json_encode if you are using PHP for the generation

PHP and JSON using Yahoo Fantasy Sports API

I am trying to query and parse Yahoo fantasy sports data and show results in a friendly format.
Here is the JSON I get back from Yahoo from a successful request...
{
"fantasy_content": {
"xml:lang": "en-US",
"yahoo:uri": "\/fantasy\/v2\/users;use_login=1\/teams",
"users": {
"0": {
"user": [
{
"guid": "1234567890"
},
{
"teams": {
"0": {
"team": {
"team_key": "268.l.auto.t.209996",
"team_id": "209996",
"name": "Team Test",
"type": "auto"
}
},
"1": {
"team": {
"team_key": "273.l.auto.t.27741",
"team_id": "27741",
"name": "Team API",
"type": "auto"
}
},
"count": 2
}
}
]
},
"count": 1
},
"time": "29.808044433594ms",
"copyright": "Data provided by Yahoo! and STATS, LLC",
"refresh_rate": false
}
}
I am looking to get the team names from the teams array. I have tried using the following PHP code (among countless variations of it) to drill to the node I need but I am not having any luck.
$obj=json_decode($json);
$data = $obj->fantasy_content->users->user->teams->team;
foreach($data as $d){
echo 'name: ' . $d->name ; //prints php
}
I am hoping that someone might be able to provide a working example using the JSON above as I have clearly failed at this. Any help would be greatly appreciated.
Thanks in advance!
Try this
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
foreach($data as $d){
echo 'name: ' . $d->team->name ; //prints php
}
EDIT
you can use the cout to loop through the names
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
for($i = 0; $i < $data->count; $i++){
echo 'name: ' . $data->{$i}->team->name ; //prints php
}

How to extract Open Graph info from TXT file?

I have a TXT file containing some facebook Open Graph info like this:
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes?format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
In PHP, I want to extract all the id numbers from the rows that show
"id": "XXXXXXXXXXXX",
The output should look like this:
I like 8277564344063
I like 243564344063
I started the following but I am getting an error:
<?php
$file_handle = fopen("raw.txt", "rb");
ob_start();
$text = file_get_contents('raw.txt');
$decode = json_decode($text);
print_r($decode);
$new_content = ob_get_clean();
file_put_contents("likes.txt", $new_content);
fclose($file_handle);
?>
The error is that my output is blank! What am I doing wrong?
Please help?
You don't have valid JSON.
The JSON Object below this line is valid JSON. I removed the comma after your last associative array within your "data" array. You shouldn't need a comma at the end of the array.
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes? format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
Parse error on line 14:
... }, ], "paging": {
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As I removed the comma from the non-valid JSON. I was able to get the result you wanted.
<?php
$json_object = file_get_contents('fb.json');
if(!$json_object) {
echo "oops, cant read the file";
}
// remap json_object
$json_object = json_decode($json_object,true);
foreach($json_object['data'] as $item) {
$items[] = "I like" . ' ' . $item['id'];
/* If you want to just echo " I like xyz" etc
* use echo "I like" . $item['id'];
*/
}
$list = implode(',',$items);
echo $list;
?>

Categories