Marco.org

I’m : a programmer, writer, podcaster, geek, and coffee enthusiast.

How to output RSS or other XML with PHP

Dear internet,

It is never OK to attempt to generate XML in your web application (e.g. an RSS feed) by manually outputting tags as strings and attempting to escape the necessary values yourself.

Here is an example of how NOT to generate XML:

<item><?= $value ?></item>

Here’s another way NOT to do it:

echo '<item>' . $value . '</item>';

The correct way to generate XML is to use the DOM. You don’t even need to worry about escaping. Here’s how that works in PHP 5:

$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('rss');
$root->setAttribute('version', '2.0');
$dom->appendChild($root);

/* for each of your items... { */
    $item = $dom->createElement('item');
    $title = $dom->createElement('title');
    $title->appendChild(
        $dom->createTextNode('Item title <unescaped>')
    );
    /* ...other item content... */
    $root->appendChild($item);
/* } */

header('Content-Type: text/xml');
echo $dom->saveXML();

Love, Marco