PHP Create an XML file using XMLWriter


Instantiate a XMLWriter object:

$xml = new XMLWriter();

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


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:


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->writeAttribute('bar', 'baz');
$xml->writeCdata('Lorem ipsum');

This will output:

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