I am pretty sure there is libraries out there that ease the creation of RSS feeds, but if you want to do it with a proper XML extension, here is an example with DOM:
First we define the namespace. This is for laziness only.
$namespaces = array(
'xmlns' => 'http://purl.org/rss/1.0/',
'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'xmlns:slash' => 'http://purl.org/rss/1.0/modules/slash/',
'xmlns:taxo' => 'http://purl.org/rss/1.0/modules/taxonomy/',
'xmlns:dc' => 'http://purl.org/dc/elements/1.1/',
'xmlns:syn' => 'http://purl.org/rss/1.0/modules/syndication/',
'xmlns:admin' => 'http://webns.net/mvcb/',
'xmlns:feedburner' => 'http://rssnamespace.org/feedburner/ext/1.0'
);
Next you need to create and setup a new Document. We want nicely formatted UTF8 XML:
// prepare DOMDocument
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = TRUE;
$dom->preserveWhitespace = FALSE;
Next you need to create a root element and add all the namespaces to it. Because we have the namespaces in an array, we can simply iterate over the array and add them:
// create root node
$root = $dom->createElement('rdf:RDF');
foreach($namespaces as $ns => $uri) {
$root->setAttributeNS('http://www.w3.org/2000/xmlns/', $ns, $uri);
}
$dom->appendChild($root);
The remainder is creating and adding nodes. This is always the same. Create Node, configure it, append it to the parent element. The code below is equivalent to your concatenated strings:
// create and append Channel
$channel = $dom->createElement('channel');
$channel->setAttribute('rdf:about', 'foo');
$root->appendChild($channel);
// create and append Title and Description
$channel->appendChild($dom->createElement('title', 'Example Feed'));
$channel->appendChild($dom->createElement('description'));
// special chars like & are only automatically encoded when added as DOMText
$link = $dom->createElement('link');
$link->appendChild($dom->createTextNode('http://example.com?foo=1&bar=2'));
$channel->appendChild($link);
// we added namespaces to root, so we can simply add ns'ed elements with
$channel->appendChild($dom->createElement('dc:language', 'en'));
$channel->appendChild($dom->createElement('dc:rights', 'public domain'));
And that's it. Now to output, you do:
// output cleanly formatted XML
echo $dom->saveXML();