Can't deal with foreach levels with JSON decoding - php

I've been dealing with this problem around 5 hours, so I think that's time to ask here.
I'm retrieving data using Facebook Graph API and using JSON decoding to put it all together on a PHP.
Here's FB Graph:
{
"feed": {
"data": [
{
"message": "A file.",
"id": "831407506978898_831408573645458",
"attachments": {
"data": [
{
"target": {
"id": "1041214692589250",
"url": "https://www.facebook.com/download/A-PDF-FILE.pdf"
},
"title": "Clase 01 - Vías de administración.pdf",
"type": "file_upload",
"url": "https://www.facebook.com/download/A-PDF-FILE.pdf"
}
]
}
},
{
"picture": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"message": "A photo.",
"id": "831407506978898_831408496978799",
"attachments": {
"data": [
{
"description": "A photo.",
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"width": 720
}
},
"target": {
"id": "10207838160017396",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
},
"type": "photo",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
}
]
}
},
{
"picture": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"id": "831407506978898_831408450312137",
"attachments": {
"data": [
{
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"width": 720
}
},
"target": {
"id": "10207838168217601",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
},
"type": "photo",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
}
]
}
},
{
"message": "TEST",
"id": "831407506978898_831407576978891"
},
{
"id": "831407506978898_831407516978897"
}
],
"paging": {
"previous": "https://graph.facebook.com/...alotofjunk"
}
},
"id": "0000000000000"
}
And my PHP is the following one:
<?php
header('Content-Type: text/html; charset=utf-8');
$limit = 60; // The number of posts fetched
$access_token='TOKEN NUMBER';
$group_id = 'GROUPNUMBER';
$url1 = 'https://graph.facebook.com/'.$group_id.'?access_token='.$access_token;
$des = json_decode(file_get_contents($url1)) ;
$url2 = "https://graph.facebook.com/{$group_id}/feed?access_token={$access_token}";
$data = json_decode(file_get_contents($url2));
?>
<?
$counter = 0;
foreach($data->data as $d) {
if($counter==$limit)
break;
?>
<? $themessage = (isset($d->message) ? $d->message : false); ?>
<? print $themessage ?>
<? $thepicture = (isset($d->picture) ? $d->picture : false); ?>
<? print "<img src=\"$thepicture\">" ?>
<!--THE PROBLEM IS FROM HERE.... -->
<?
$counter = 0;
foreach($d->attachments->data as $d2) {
if($counter==$limit)
break;
?>
<? $attachments = (isset($d2->url) ? $d2->url : false); ?>
<? print $attachments ?>
<?
}
?>
<!-- ...TO HERE -->
<?
$counter++;
}
?>
I get a perfect output of $themessage and $thepicture, but I with $attachments I receive the following errors:
Notice: Undefined property: stdClass::$attachments in...
Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...
I've already read this: Trouble with Facebook multi-level json php foreach loop, but no luck.
How can I fix this?. Thanks a lot!

You need to be careful when you're chaining objects - especially in loops. One empty object will bring down the whole show. Try this:
$counter = 0;
if( isset( $d->attachments ) )
{
foreach( $d->attachments->data as $d2 )
{
....
}
}

Notice: Undefined property: stdClass::$attachments in...
Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...
You're getting this error becoz you're missing feed object in your first loop
HereDEMO
Replace
foreach($data->data as $d) {
if($counter==$limit)
break;
?>
With
foreach($data->feed->data as $d) {
if($counter==$limit)
break;
?>
Your JSON is in this format paste your JSON here JSON Format Viewer and check it
I tried your code i'm able to get url printed HereDEMO
$data="Your JSON Here"
foreach($data->feed->data as $d) {
$themessage = (isset($d->message) ? $d->message : false);
print("\n".$themessage);
$thepicture = (isset($d->picture) ? $d->picture : false);
print("\n<img src='$thepicture'>");
foreach($d->attachments->data as $d2) {
$attachments = (isset($d2->url) ? $d2->url : false);
print("\n".$attachments);
}
}
Side Note: you're initailising $counter = 0; twice once inside loop
and outside the loop its bad Even for $attachment, Its my opinion after looking your code for first time whatever you're reason be behind it

Related

Getting data from nested arrays in json with php

I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2

json, php - output string from array

I am trying to decode JSON data to PHP then output it to the site. If I have the following:
{
"name": "josh",
"type": "human"
{
I can do this (within PHP), to display or output my type:
$file = "path";
$json = json_decode($file);
echo $json["type"]; //human
So, if I have the following:
{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}
How can I output what type my friend ben is?
Use a loop like foreach and do something like the following:
//specify the name of the friend like this:
$name = "ben";
$friends = $json["friends"];
//loop through the array of friends;
foreach($friends as $friend) {
if ($friend["name"] == $name) echo $friend["type"];
}
To get the decoded data in array format you would supply true as the second argument to json_decode otherwise it will use the default which is object notation. You could easily create a function to shorten the process when you need to find a specific user
$data='{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}';
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $friend ){
if( $friend->name=='ben' )echo $friend->type;
}
function finduser($obj,$name){
foreach( $obj as $friend ){
if( $friend->name==$name )return $friend->type;
}
}
echo 'Tom is a '.finduser($friends,'tom');
try this,
$friend_name = "ben";
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $val){
if($friend_name == $val->name)
{
echo "name = ".$val->name;
echo "type = ".$val->type;
}
}
DEMO

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

Json php formatted data

I have a json file like this
{
"id": "123456789012345",
"members": {
"data": [
{
"name": "Dylan John",
"administrator": false,
"id": "12341234"
},
{
"name": "Test user",
"administrator": false,
"id": "43214321"
},
{
"name": "Demo user",
"administrator": false,
"id": "55445544"
},
{
"name": "Fake user",
"administrator": false,
"id": "11991199"
}
],
"paging": {
"next": "www.123456demo12345.com"
}
}
}
I need to extract the id of each name.
I just start my php code like that but simply display only the master id:
<?php
$url = "http://www.1234demo1234fake.com/user.json";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[id]; //echo master id
echo $data[members][data][id];
?>
You have to iterate over $data['members']['data'] and print $data['members']['data'][$i]['id'].
Your JSON object contains property members again members has property data.
Now data is an array.
Just loop over data, you get array of objects (members), fetch property id from it.
<?php
$abc = json_decode($your_json_sting);
$membersData = $abc->members->data;
$memberIds = array();
foreach ($membersData as $mem) {
$memberIds[] = $mem->id;
}
echo '<pre>';print_r($memberIds);echo '</pre>';
?>

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