Search code examples
phpxmlrsssimplexml

Printing thumbnails using simpleXML parse - how to return all?


I have looked for this answer to this question on here but I can't seem to find anything which is relevant to this particular issue.

I am currently using simpleXML to parse an RSS feed, in order to return thumbnail images by going through the nodes to parse "media:thumbnail". I have managed to do this and return all thumbnail URLs, so I know that I am getting to the right content, like so:

<?php 

$url = "http://feeds.bbci.co.uk/news/rss.xml?edition=uk";
$xml = simplexml_load_file($url);

foreach($xml->channel->item as $item) {
$media = $item->children('media', 'http://search.yahoo.com/mrss/');
foreach($media->thumbnail as $thumb) {
   echo $thumb->attributes()->url;
}
}

?>

This echos all the image urls. But when I store this in to a variable and try to echo this later as the img src, it only returns one image, rather than all:

<?php 

$url = "http://feeds.bbci.co.uk/news/rss.xml?edition=uk";
$xml = simplexml_load_file($url);

foreach($xml->channel->item as $item) {
$media = $item->children('media', 'http://search.yahoo.com/mrss/');
foreach($media->thumbnail as $thumb) {
   $image = $thumb->attributes()->url;
}
}
?>

<div><img src = <?php echo $image; ?> /></div>

How can I echo all of the URLs in to individual images? Thanks for looking.


Solution

  • Since you're getting and expecting multiple image urls, might as well store them inside an array:

    $images_container = array();
    foreach($xml->channel->item as $item) {
        $media = $item->children('media', 'http://search.yahoo.com/mrss/');
        foreach($media->thumbnail as $thumb) {
           $image = $thumb->attributes()->url;
           $images_container[] = (string) $image;
        }
    }
    
    echo '<pre>', print_r($images_container, 1), '<pre>';
    

    Sample Output

    Now of course, if you want to process those array of string image urls, then just use and process the container:

    <?php foreach($images_container as $url): ?>
        <div><img src="<?php echo $url; ?>" alt="" /></div>
    <?php endforeach; ?>
    

    Pictures