Add rss xmlns namespace definition to php simplexml document?

I'm trying to create an itunes-valid podcast feed using php5 simplexml:

<?php   
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>


<channel>
</channel>
XML;

$xml_generator = new SimpleXMLElement($xml_string);
           $tnsoundfile = $xml_generator->addChild('title', 'Main Title');
           $tnsoundfile->addChild('itunes:author', "Author", ' ');
           $tnsoundfile->addChild('category', 'Audio Podcasts'); 
           $tnsoundfile = $xml_generator->addChild('item');
           $tnsoundfile->addChild('title', 'The track title');        
           $enclosure = $tnsoundfile->addChild('enclosure');
           $enclosure->addAttribute('url', 'http://test.com');
           $enclosure->addAttribute('length', 'filelength');
           $enclosure->addAttribute('type', 'audio/mpeg');       
           $tnsoundfile->addChild('itunes:author', "Author", ' '); 


header("Content-Type: text/xml");
echo $xml_generator->asXML();

?>

      

It doesn't check because I need to put the line:

<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">

      

according to http://www.apple.com/itunes/podcasts/specs.html .

So the output MUST be:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
<channel>

      

etc .. I've been over and over the guide and forums, just can't figure it out. If I put, near the footer:

header("Content-Type: text/xml");
echo '<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">';
echo $xml_generator->asXML();
?>

      

Then it looks correct in firefox and it no longer complains about undefined namespaces, but the feedvalidator complains that

line 1, column 77: XML parsing error :: 1: 77: xml declaration not at the beginning of an external object [help]

because now the document starts:

<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"><?xml version="1.0" encoding="UTF-8"?>

      

but not

<?xml version="1.0" encoding="UTF-8"?><rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">

      

+2


a source to share


2 answers


This is very possible with SimpleXML. Just declare the namespace inside the constructor string, not as an attribute.



$rss_xml = new SimpleXMLElement(
   '<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"/>');
$rss_xml->addAttribute('version', '2.0');

      

+2


a source


The code shown in the question doesn't work because it doesn't use the correct namespace. Specifically, these lines:

$tnsoundfile->addChild('itunes:author', "Author", ' ');

      

They will create a <author/>

node in the single-space namespace, which is clearly not true. It should read:



$tnsoundfile->addChild('itunes:author', "Author", 'http://www.itunes.com/dtds/podcast-1.0.dtd');

      

This is the correct way to use namespaces.

+3


a source







All Articles