the PHP5 XMLWriter class allows to easily create XML well-formed documents.

The most useful methods:
  • openURI($output) // use ‘php://output‘ as argument to stream directly
  • startDocument(‘1.0’) // add the initial tag. 1st argument : xml version
  • writeElement(‘hr’) // write the empty node [hr/]
  • writeAttribute(‘src’,’img.gif’) //write the attribute (inside the last node) and value
    e.g: [img src=”http://www.blogger.com/img.gif” /]
  • writeElement(‘b’,’content’) // write node with content “[b]content[/b]”
  • startElement(‘body’) //add the start node [body]
  • endElement() //close the last element started. e.g: [/body]
  • How to create nodes with attributes and text:
    text(‘default text’)

    [textarea name=”area”]default text[/textarea]
  • endDocument()
  • flush()
  • there are other methods to write comments, DTD, CData etc… view the official documentation.
Note: I used square brackets instead of “minor or greater than” because of blogspot editor limitation.

Complete Example: RSS Feed !!

$xml = new XMLWriter();
// Output directly to the user
$xml->writeAttribute(‘version’, ‘2.0’);
$xml->writeAttribute(‘xmlns:atom’, ‘http://www.w3.org/2005/Atom’);


//title, desc, link, date
$xml->writeElement(‘title’, ‘PHP news’);
$xml->writeElement(‘description’, ‘description….’);
$xml->writeElement(‘link’, ‘http://www.example.com/rss.hml’);
$xml->writeElement(‘pubDate’, date(“D, d M Y H:i:s e”));

//item !
$xml->writeElement(‘title’, ‘news 1’);
$xml->writeElement(‘link’, ‘http://www.example.com/1.html’);
$xml->writeElement(‘description’, ‘descr 1’);
$xml->writeElement(‘pubDate’, date(“D, d M Y H:i:s e”));
$xml->writeAttribute(‘domain’, ‘http://www.example.com/cat1.htm’);
//end item
//end channel
// end rss
//end doc