Using PHP SimpleXML to manipulate itunes compatible RSS/ Podcast XML (work around)

Posted: June 13th, 2012 | Author: | Filed under: PHP | Tags: , , , , , | No Comments »

PHP’s SimpleXML is very easy to use and is perfectly suited to generate and update mundane things like Postcast RSS.

To create an XML object from an RSS file in PHP. All you need is to do to use the simple_loadxml_file command. eg

$xml = simple_loadxml_file('rss.xml');

. To change attributes is very easy, you only need to typecast the variable name and point to the new value eg

(string)$xml->channel->pubDate = date(DATE_RFC822);

.

Everything is all fun and games until you get to the iTunes podcast specifications. For pocasts, Apple has added a few special tags that have the itunes: prefix. eg owner, name, email, category etc. The problem is not with the words but with the ‘:’. XML uses colon symbol to specify a namespace, which in turns causes SimpleXML to get confused when it is processing the iTunes specific tags. If you use a command like addChild to add an itunes:author tag eg

$rssitem->addChild('itunes:author', $rssauthor);

It will be rendered as

<author>Joe Bob</author>

.

For generating a Podcast feed, I am assuming you will be updating the feed from an existing file instead of generating it from scratch every time it needs updating. I suggest you save the XML file into 2 copies, one for internal / coding use and one for public podcast XML. In the private one, you will use SimpleXML as is and generate tags with iti_ prefix instead of itunes: prefix eg

<iti_author> Bob</iti_author>

instead of

<itunes:author> Bob</itunes:author>

. After you have processed and saved the XML object, use str_replace(‘iti_’, ‘itunes:’, $xmlfile) to replace the tags and that will be the public XML feed file.

After entering all the info into the XML file, you would need to run it through the DOM object to clean up the entry, it makes the XML readable. Here is the snippet of the code:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$dom->save('yourfeedname.xml')

This way is much quicker than trying to get SimpleXML to work with not quite conforming specifications of iTune’s XML.

Reference(s):