Question

I'm a bit of a newbie in PHP programming, and have been Googleing and trying for hours now to get this to work. However, I'm out of luck. Hopefully someone can help me :-)

What I'm trying to do is to use the Last.FM API to get the cover image of a single track. It works when it finds a image tag in the XML, but as soon as the isn't in the XML file from Last.FM the PHP script outputs a lot of errors and still tries to insert a broken image in the document. What I want to do is if the script finds the image tag in the XML it displays the image and if it doesn't find it, display a generic image.

This is my code so far (The URL to the XML file here is working with the image);

<?php
$img = simplexml_load_file('http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=f5f149ffcdf2e0db0888f6c477c4abc1&artist=cher&track=believe');
echo '<img src="';
echo $img->track[0]->album[0]->image[3];
echo '">';
?>

I've tried everything, but I can't figure it out. Anyone wants to help me with this?

Was it helpful?

Solution

You can query for that image with xpath and if there is no result, provide a default src value.

Additionally you should encode the HTML that you create:

list($src) = $img->xpath('/*/track[1]/album[1]/image[4]')?
             :['http://example.com/path/to/default.png'];

printf('<img src="%s">', htmlspecialchars($src));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top