PHP SimpleXML
A quick article on PHP's SimpleXML.
SimpleXML provides a simple and practical way of reading and handling XML content. SimpleXML requires PHP5.
First you define your XML document source:
$xml = new SimpleXMLElement(file_get_contents('http://example.com/rss/'));
Then you choose what structure to get from the XML, in this example I want to loop through all the <item> tags under the first <channel>. Then I want to view the <title> of each item, as well as a download count from the 'download' namespace. The XML could look something like this:
<?xml version="1.0" encoding="UTF-8" ?> <rss xmlns:download="http://example.com/rss/downloadModule#" version="2.0"> <channel> <item> <title>The Title</title> <download:count>12345</download:count> </item> <item> <title>The Title 2</title> <download:count>1234</download:count> </item> </channel>
SimpleXML works through arrays. Here I'm telling it to loop through the first <channel> by writing 'channel[0]', and then the item collection within that channel. This small example illustrates how to handle both normal tags and namespaces.
foreach( $xml->channel[0]->item as $item ) { // The download namespace $download = $item->children('http://example.com/rss/downloadModule#'); // View item title echo $item->title; // The download count echo $downloads->count; }
I haven't had any need for it yet, but to get the attributes within a tag you should only have to do something like this:
$attributes = $item->attributes(); // View attributes through names: echo $attributes->attribute1; echo $attributes->attribute2;