This is a bit of a noob question. I’m working with a JSON file which looks something like this:
{"nodes":
[{"node":
{"Vocabulary name":"Bestseller Format",
"Term":"Hardcover Fiction",
"Bestseller1":"9780470227800",
"Bestseller2":"9781451617962",
"Bestseller3":"9781439167397",
"Bestseller4":"9781617750106",
"Bestseller5":"9780385533300",
"Bestseller6":"9780670022526",
"Bestseller7":"9781609530358",
"Bestseller8":"9780132358040",
"Bestseller9":"9780596159771",
"Bestseller10":"9780151014163",
"Bestseller11":"9780393334807",
"Bestseller12":"9780805090161"}
}]
}
And I am trying to parse it in php. I have come up with a script
<?php
$jsonurl = "http://www.xtracrunchy.com/pandpnewlook/?q=pandp/bestsellers";
$json = file_get_contents($jsonurl,NULL, NULL, 0, 1000);
$json_output = json_decode($json,true);
$bestseller_array = $json_output[nodes][0][node];
foreach ($bestseller_array as $key => $value)
{
print $key;
print " - ";
print $value;
print "<br />";
}
?>
I would like to be able to eventually build an ordered list of Bestseller ISBN’s but the only output I get when I run this script is
Vocabulary name – Bestseller Format
Term – Hardcover Fiction
and when I add print count($bestseller_array); I only get 2 elements in the array.
Any help would be appreciated.
First of, I strongly advise you make use of CURL instead of
file_get_contents(), because in some occasions, it won’t work. But since it’s not a part of the question, I won’t talk about this any further.Secondly, you’re making use of unnamed literal constants, which is very bad.
Should be:
See the documentation here on why.
Finally, the JSON string you wrote above doesn’t match with what is returned on that url, and the script does work as expected on this “new” json.