According to your reply in the comments, my hypothesis is confirmed.
Because you are requesting the Last.FM API to return JSON, you get the error:
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML
Because it is JSON, not XML.
You can fix this in two ways. Either change the response format to XML or do not use SimpleXML
but json_decode()
instead.
The first is probably the easiest to adjust. Try to change the &format=json
part to &format=xml
I haven't tested this but highly probably that this will be supported by Last.fm.
Also note that you don't supply an image size, and "image_mega" the default value is not a valid value (see API specs @ http://www.last.fm/api/show/artist.getInfo). You probably want want to use "mega" not "image_mega"
Updated, working code using JSON:
<?php
class LastFM {
const API_KEY = "7facb82a2a573dd483d931044030e30c";
public static $size_map = array("small" => 0, "medium" => 1, "large" => 2, "extralarge" => 3, "mega" => 4);
public static function getArtwork($artist, $return_image = false, $size = "mega", $album) {
$artist = urlencode($artist);
$album = urlencode($album);
$returnedInfo = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=" . self::API_KEY . "&artist=" . $artist . "&album=" . $album . "&image=" . self::$size_map[$size] . "&format=json";
$returnedInfo = @file_get_contents($returnedInfo);
if(!$returnedInfo) {
return; // Artist lookup failed.
}
$json = json_decode($returnedInfo, true);
$albumArt = $json["artist"]["image"][self::$size_map[$size]]["#text"];
return (!$return_image) ? print_r($json) : '<img src="' . $albumArt . '" alt="' . urldecode($artist) . '" />';
}
}
$artist = "Daft Punk";
$album = "Random Access Memories";
$size = "mega";
$artwork = LastFM::getArtwork($artist, true, $size, $album);
if($artwork) {
echo $artwork;
}
else{
return;
}
I know I rock. I choose JSON because I find it easier to work with. It returns exactly what you want, e.g.:
<img src="http://userserve-ak.last.fm/serve/500/10923145/Daft+Punk+6a00e398210d13883300e55ui6.png" alt="Daft Punk" />
Finally, I added urlencoding()
for the album name, since I had issues with that in my example.