This is the code, it use a foreach to access to department and workers .
EDIT: Will correct several paste errors
<?php
$json = '{
"boss": "Jeff",
"department": [{
"office": "1111",
"workers": "[{\"id_work\":\"123\",\"name\":\"mike\",\"mobile\":\"12345\"}]"
}]}';
$json_data = json_decode($json);
echo "Boss:".$json_data->boss;
echo "<br>";
foreach($json_data->deparment as $dep)
{
echo "Office number:".$dep->office."<br>";
foreach($dep->workers as $worker){
echo "Worker ID: ".$worker->id_work."<br>";
echo "Worker name : ".$worker->name."<br>";
echo "Worker mobil: ".$worker->mobil."<br>";
}
}
?>
I cannot access to internal array when I try do a foreach() this happens :
Invalid argument supplied for foreach()
How I can access to the information of the nested array
The json data inside $json is wrong. The decode didn't gave errors but the array you get back is not how you want it to be, that's why you get errors after json_decode.
The error you got was because the worker value is in string format.
You should update that:
From: "workers": "[{\"id_work\":\"123\",\"name\":\"mike\",\"mobile\":\"12345\"}]"
To: "workers": [{ "id_work": "123", "name": "mike", "mobile":"12345"}]
End result:
$json = '{
"boss": "Jeff",
"department": [{
"office": "1111",
"workers": [{ "id_work": "123", "name": "mike", "mobile":"12345"}]
}]}';
$json_data = json_decode($json);
echo "Boss:".$json_data->boss;
echo "<br>";
foreach($json_data->department as $dep)
{
echo "Office number:".$dep->office."<br>";
foreach($dep->workers as $worker){
echo "Worker ID: ".$worker->id_work."<br>";
echo "Worker name : ".$worker->name."<br>";
echo "Worker mobil: ".$worker->mobile."<br>";
}
}
Related
am having issues trying to get contents of this json, am using php.
{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}
this is my function, that returns the json
public function getSong($id) {
$song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
$api = Api::getSpotOn($song_url);
$song = $api->{'song'};
return $song;
}
I want to get all it content.
Thanks!
In the json example you provided a final '}' is missing and the json_decode will return Null without it as it's non a valid json.
But, since you have the getSong method the following should work:
$retObject = json_decode(getSong($songId));
$song = $retObject->song;
print_r($song);
echo 'returncode:'.$song->returncode.'<br/>';
echo 'returnmsg:'.$song->returnmsg.'<br/>';
echo 'title:'.$song->title.'<br/>';
echo 'artist:'.$song->artist.'<br/>';
echo 'album:'.$song->album.'<br/>';
echo 'size:'.$song->size.'<br/>';
echo 'url:'.$song->url.'<br/>';
echo 'time:'.$song->time.'<br/>';
echo 'date:'.$song->date.'<br/>';
echo 'source:'.$song->source.'<br/>';
echo 'active:'.$song->active.'<br/>';
echo 'albumart:'.$song->albumart.'<br/>';
echo 'speed:'.$song->speed.'<br/>';
echo 'counter:'.$song->counter.'<br/>';
try the following:
$result = json_decode(
'{
"song": {
"returncode": "200",
"returnmsg": "OK",
"title": "Despacito Ft. Justin Bieber",
"artist": "Luis Fonsi, Daddy Yankee",
"album": "",
"size": "9193600",
"url": "http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3",
"time": "1499079781",
"date": "Jul 3, 2017",
"source": "",
"active": "1",
"albumart": "https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg",
"speed": "21",
"counter": "850850"
}
}'
);
var_dump($result);
echo $result->song->title;
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;
}
?>
I'm trying to retrieve JSON Objects on my localhost, the issue is that it wont output anything. The JSON objects could look like following:
[
{
NAME: "Hearthstone",
PLAYER1: "Rdu ",
PLAYER2: "Savjz ",
status: 2,
meta: "LIVE"
},
{
NAME: "League of Legends",
PLAYER1: "Team King ",
PLAYER2: "EDG ",
status: 2,
meta: "28.12."
}]
php retrieve objects.
$url = "http://localhost:8888/crawl_JSON.php";
$json = file_get_contents($url);
$json_output = json_decode($json);
echo $json_output;
Why don't it output anything?
Note that json_decode() returns an object, you cannot echo you will need to use var_dump or print_r. If you want to echo , you can echo the JSON string.
$url = "http://localhost:8888/crawl_JSON.php";
$json = file_get_contents($url);
echo $json;
$json_output = json_decode($json);
var_dump($json_output);
And inside of crawl_JSON.php You need to echo the JSON, you will need to make sure it is valid.
<?php
echo '
[
{
"NAME": "Hearthstone",
"PLAYER1": "Rdu ",
"PLAYER2": "Savjz ",
"status": 2,
"meta": "LIVE"
},
{
"NAME": "LeagueofLegends",
"PLAYER1": "TeamKing",
"PLAYER2": "EDG",
"status": 2,
"meta": "28.12."
}
]
';
I've this JSON string:
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
}
}';
I'd like to print every single entry on a webpage using php and then save these entries on a mysql db.
In the db there is already a "code", "name" and "link" field..
This is what I've tried without luck (to print the stuff on a page):
$obj = json_decode($json,true);
echo ($obj["bigprodlist"]["prods"][0]["name"]);
Thank you very much for the help
First, fix your JSON missing end bracket that makes JSON decoding fail (add the ] after the prods data ), then expand your echo statement with some foreach loops to get the data printed. This is only a simple example to get you on the right track:
foreach ($obj["bigprodlist"]["prods"] as $p):
echo "<div>";
foreach ($p as $name=>$value):
echo "<span>".$name.": ".$value."</span>";
endforeach;
echo "</div>";
endforeach;
You can then use the same loop procedure to get the data into your DB.
You need to use json_last_error(); http://no1.php.net/manual/en/function.json-last-error.php
Debugging:
$obj = json_decode($json,true);
var_dump($obj, json_last_error());
You are missing a ] :
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
] //missing!
}
}';
Where did you get json output?
It's invalid:
Parse error on line 18:
... } } }
----------------------^
Expecting ',', ']'
Check your json at http://jsonlint.com/
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;
?>