Tomi Seus
Tomi Seus

Reputation: 1161

Getting media:thumbnail from XML

I just can't seem to be able to solve this. I want to get the media:thumbnail from an RSS file (http://feeds.bbci.co.uk/news/rss.xml).

I did some research and tried to incorporate insights from https://stackoverflow.com/questions/6707315/getting-xml-attribute-from-mediathumbnail-in-bbc-rss-feed and from other sources.

This is what I got:

$source_link = "http://feeds.bbci.co.uk/news/rss.xml";
$source_xml = simplexml_load_file($source_link);
$namespace = "http://search.yahoo.com/mrss/";

foreach ($source_xml->channel->item as $rss) {
    $title          = $rss->title;
    $description    = $rss->description;
    $link           = $rss->link;
    $date_raw       = $rss->pubDate;
    $date           = date("Y-m-j G:i:s", strtotime($date_raw));
    $image          = $rss->attributes($namespace);

    print_r($image);
}

When I run the script, all I see is a white page. If I echo or print_r any of the other variables, then it works like a charm. It's just the $image one which poses problems. Why isn't this working? Thx for any help!

Upvotes: 3

Views: 8490

Answers (3)

Kevin Perdana
Kevin Perdana

Reputation: 11

Base from this blog, with post title Processing media:thumbnail in RSS feeds with php.

The solution that I found works best simply loads the xml file as a string, then find and replace 'media:thumbnail' with a correctly formatted 'thumbnail' and lastly convert it back to xml with simplexml_load_string:

$xSource = 'http://feeds.bbci.co.uk/news/rss.xml';
$xsourcefile = file_get_contents( $xSource );

$xsourcefile = str_replace("media:thumbnail","thumbnail",$xsourcefile);
$xml = simplexml_load_string( $xsourcefile );
echo $row['xtitle'] . '<BR>';

foreach ($xml->channel->item as $item) {
echo ':' . $item->title . '<BR>';
echo ':' . $item->thumbnail['url'] . '<BR>';
}

Upvotes: 1

Tomi Seus
Tomi Seus

Reputation: 1161

OK, it works now. I replaced

$image = $rss->attributes($namespace); 

with

$image = $rss->children($namespace)->thumbnail[1]->attributes();
$image_link = $image['url'];

and it works like a charm now.

Upvotes: 8

Francis Avila
Francis Avila

Reputation: 31621

$image          = $rss->attributes($namespace);

This says "Give me all attributes of this <item> element which are in the media namespace". There are no attributes on the item element (much less any in the media namespace), so this returns nothing.

You want this:

$firstimage = $rss->children($namespace)->thumbnail[0];

BTW, when you use SimpleXML you need to be careful to cast your SimpleXMLElements to string when you need the text value of the element. Something like $rss->title is a SimpleXMLElement, not a string.

Upvotes: 0

Related Questions