Kurt Leadley Kurt Leadley - 4 months ago 14x
PHP Question

Parsing JSON with PHP array/object confusion

I am trying to parse this JSON data to print on a fanpage I am working on.
If you look at that JSON link, you will see that the structure is

. I recently learned how to parse JSON with a slightly different structure like this JSON file, where the data structure is

Here is my code I am attempting:(I have tried about 10 variations of this with explodes for the commas too)

$json = file_get_contents('http://live.nhl.com/GameData/SeasonSchedule-20152016.json');

$json = json_decode($json, TRUE);

foreach($json as $d){
$estTime = $d['est'];
echo $estTime;

As I said, I had some success with that other structure of JSON I linked by doing this:

$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');

$json = json_decode($json, TRUE);

$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];

foreach($skaterData as $d){
$stats = explode(',', $d['data']);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];

Edit: JSON data successfully parsed


The only thing wrong with your code is that you are missing the closing curly bracket to your foreach.

I would strongly recommend paying attention to the error messages you get, often they will let you easily solve the problem. If your server does not display them in the browser (this is usually a good thing on live sites), you will find them in an error log somewhere on the server.

Additionally you may want to use a proper editor with linting (what is linting), which would probably have immediately notified you of this omission one way or another. One such free tool is Atom.