Monday, July 6, 2009

XML - Parse RSS media:thumbnail with simpleXML

PHP 5's simpleXML treats an RSS media:thumbnail entry as if it were a namespace. simpleXML doesn't have a built in fix for this, so I had to create my own.

I won't share the rest of the secrets of that project with you, but feel free to use my code on your own project.

Thanks,

<!-- For RSS media feeds of the following format: ( channel/item/{title, description, link, GUID, media:thumnail[url]} ) -->

<table>
<?php
// I wrote this to accept a POST or GET from a webform
// You can also send the 'xmlurl' variable like this:
// http://www.mysite.com/mypage.php?xmlurl=SITEURLHERE
$xmlURL = $_REQUEST('xmlurl');

$entries = new SimpleXMLElement('$xmlURL', null, true);

foreach ($entries->channel->item as $item)
{
foreach ($item->xpath ('media:thumbnail') as $mediathumbnail) {
$thumb = $mediathumbnail['url'];
}
foreach ($item->children() as $child)
{
switch ($child->getName())
{
case 'title':
$title = $child;
break;

case 'link':
$link = $child;
break;

case 'description':
$description = $child;
break;

default:
break;
}
}
echo "";
echo "<tr><td><a href='".$link."' target='_blank'><img src='".$thumb."'></a></td>";
echo "<td><a href='".$link."' target='_blank'>".$title."</a><br>".$description."</td><tr>";
echo "";
}
?>
</table>