PHP Create an XML file using XMLWriter


Example

Instantiate a XMLWriter object:

$xml = new XMLWriter();

Next open the file to which you want to write. For example, to write to /var/www/example.com/xml/output.xml, use:

$xml->openUri('file:///var/www/example.com/xml/output.xml');

To start the document (create the XML open tag):

$xml->startDocument('1.0', 'utf-8');

This will output:

<?xml version="1.0" encoding="UTF-8"?>

Now you can start writing elements:

$xml->writeElement('foo', 'bar');

This will generate the XML:

<foo>bar</foo>

If you need something a little more complex than simply nodes with plain values, you can also "start" an element and add attributes to it before closing it:

$xml->startElement('foo');
$xml->writeAttribute('bar', 'baz');
$xml->writeCdata('Lorem ipsum');
$xml->endElement();

This will output:

<foo bar="baz"><![CDATA[Lorem ipsum]]></foo>