Generating XML with SimpleXML and namespaces
2009-01-13 17:32:17
This isn't well documented on the php website, so I thought I would explain it here.
If you want to use namespaces in your XML, then you declare the namespace's prefix and uri in your root element, then you add the *SAME* uri as the third option in your addChild() or addAttribute() function call.
<?php
header('Content-type: text/xml');
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" />');
//main page
$channel = $xml->addChild('channel');
//atom link
$atomlink=$channel->addChild('link','','http://www.w3.org/2005/Atom');
$atomlink->addAttribute('href',$base.'/'.$script.'/rss');
$atomlink->addAttribute('rel',"self");
$atomlink->addAttribute('type',"application/rss+xml");
//snip...
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><atom:link href="http://www.tractionthroughaction.com/blog/rss" rel="self" type="application/rss+xml"></atom:link>
I hope this helps someone, it took me about 20 minutes of searching before I found it.
Mike
