GeorgeP GeorgeP - 8 months ago 55
JSON Question

Parsing a multidimensional json file with php

I've read through many similar posts but I can't seem to get it to work right. I can parse and the whole json file, it's a chart from Shazam. I'm stuck on selecting nested keys and get their values. How can I get only the artist, title and numberOfShazams values into attributes?

Here is my code so far:

<?php
$json = file_get_contents('http://cdn.shazam.com/shazam/v2/en/MX/android/-/tracks/web_chart_world');
$json_data = json_decode($json,true);
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:<br>";
} else {
echo "$key => $val<br>";
}
}
?>

Answer Source

I hope I understand you correctly, and you wanted the tracktitle, trackartist, and numberOfShazams. This works for me:

<?php
$json = file_get_contents('http://cdn.shazam.com/shazam/v2/en/MX/android/-/tracks/web_chart_world');
$json_data = json_decode($json,true);

foreach( $json_data['chart'] as $chart )
{
    echo '<p>';
    echo urldecode($chart['urlparams']['{tracktitle}']);
    echo '<br />';
    echo urldecode($chart['urlparams']['{trackartist}']);
    echo '<br />';
    echo $chart['properties']['numberOfShazams'];
    echo '</p>';
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download