SimpleXML

December 10
blog author

Appno Blogger

Appnovation Coop

Recently I had to display an RSS feed within a website. I ended up using SimpleXML class which provides a very simple and usable toolset to convert XML into an object that can be processed with normal property selectors and array iterators.

$xml = file_get_contents('http://rssfeed.com/?feed=rss'); $xml = simplexml_load_string(utf8_encode($xml)); $xml->registerXPathNamespace('c', 'http://www.google.com/schemas/sitemap/0.84'); foreach($xml->channel->item AS $item){   print '

';   print '
' . date('d-m-Y', strtotime($item->pubDate)) . '
';   print '
';   print ''.ucfirst($item->title).'';   print 'More';   print '
';   print '

'; }

Above I have attached an example of how I implemented SimpleXML. I used file_get_contents because the RSS feeds I was pulling from had a redirect which was causing the SimpleXML::construct() some problems. So, once I have the contents of the RSS feed, I load it up by using simplexml_load_string(). This loads the string version of the RSS feed and stores it as an object within the $xml variable. Next, I register a namespace within the XML document so that the namespace won’t cause issues and searching using xpath will work now. Once this is completed, I then loop around the RSS items and output the title, publish date and link for each item. My implementation of SimpleXML is fairly simple but while researching the PHP class I noticed that the SimpleXML object is very impressive and allows you to easily traverse and modify XML.

Four functions I thought were worth noting were:

a). SimpleXML::addAttribute - Allows you to add an attribute to the XML element.

b). SimpleXML::addChild - Allows you to add a child element to the XML node.

c). SimpleXML::xPath - Runs XPath query on XML document. - $xml->xpath(‘url’) -> will return an array of all occurences of “url” in the xml document.

d). SimpleXML::registerXPathNamespace - Creates a prefix/ns content for the next XPath query.

This is helpful when namespaces are included in the XML document. You have to register these namespaces otherwise xPath won’t be able to search the document. Anyways, in short, PHP5 and its introduction of SimpleXML is a huge step forward in XML management and allows developers easy manipulation of XML documents.

For more information visit: http://www.php.net/manual/en/book.simplexml.php