Question

I've been working of a project of mine, just to learn a bit more about PHP and JSON handling. I worked with the Fanart.tv API now and get everything up and running as I want, but I've run into some issues. I want to get the FIRST array in the JSON file, but everything I've tried so far doesn't do the trick.

Anyone wants to help me? Here's the JSON file I'm trying to work with;

{"Eminem":{"mbid_id":"b95ce3ff-3d05-4e87-9e01-c97b66af13d4","artistbackground":[{"id":"14795","url":"http://assets.fanart.tv/fanart/music/b95ce3ff-3d05-4e87-9e01-c97b66af13d4/artistbackground/eminem-4ed3e35d6f3da.jpg","likes":"3"}

This is my code from my PHP file that actually works;

$img = $json->Eminem->artistbackground[0]->url;

However, I want to print the image and echo the name of the artist - in this case "Eminem". I've tried with "$json[0]" and just "[0]", but then I just get error messages. Anyone know how this can be done, reading the JSON file? I get the script updating the ID in the URL ($mbid) from MusicBrainz automatically, so if it is another artist than Eminem I read the JSON file from - my code doesn't work.

This is my PHP code so far;

$backgroundURL = 'http://api.fanart.tv/webservice/artist/a93e666f14a34d979b3e3617eab2f340/'.$mbid.'/json/artistbackground/1/1';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $backgroundURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; curl)");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($ch);
curl_close($ch);

$json  = json_decode($json);
$bg = $json->Eminem->artistbackground[0]->url;

echo '<img src="'.$bg.'" height="540" width="960">'

As long as the JSON file is for the artist Eminem, it works. As soon as I get another artist, it doesn't so i need the first element in the JSON file in the $bg string.

Anyone knows how to do this? Thanks for the help!

Was it helpful?

Solution

current() function returns value of the current key (first):

$json  = json_decode($json);
$first = current($json);
$bg    = $first->artistbackground[0]->url;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top