简体   繁体   中英

PHP Last.fm Get Largest Image for an Artist

I have the following code

<?php
    $xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Metallica&api_key=b25b959554ed76058ac220b7b2e0a026");
    $artistTag= $xml->artist->children();
    $largeImage = $artistTag[7];
    echo '<img src="'.$largeImage.'" />';     
?>

This will target the 7th node - however the 7th node might not exist so this won't work. Is there anyway to specifically target the large, extralarge or mega nodes?

Example XML

<lfm status="ok">
<artist>
<name>Metallica</name>
<mbid>65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab</mbid>
<url>http://www.last.fm/music/Metallica</url>
<image size="small">
http://img2-ak.lst.fm/i/u/34s/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="medium">
http://img2-ak.lst.fm/i/u/64s/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="large">
http://img2-ak.lst.fm/i/u/174s/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="extralarge">
http://img2-ak.lst.fm/i/u/300x300/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="mega">
http://img2-ak.lst.fm/i/u/c14fdad46a5c423f86a683501c163c99.png
</image>
<image size="">
http://img2-ak.lst.fm/i/u/arQ/c14fdad46a5c423f86a683501c163c99.png
</image>

So if mega doesn't exist, go for extralarge, if that doesn't exist, go to large etc

This is possibly a duplicate of : SimpleXML: Selecting Elements Which Have A Certain Attribute Value

Here is what I would think for your particular case:

<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Metallica&api_key=b25b959554ed76058ac220b7b2e0a026");
$largeImage = $xml->xpath('/lfm/artist/image[@size="mega"]')[0];
echo '<img src="'.$largeImage.'" />';     
?>
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Metallica&api_key=b25b959554ed76058ac220b7b2e0a026");
$largeImage = $xml->xpath('/lfm/artist/image[@size="mega"]')[0];
echo '<img src="'.$largeImage.'" />'; 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM