Writing XML with PHP

20 Oct 2017 in PHP, XML

In PHP there are many different ways to create XML documents from some data. You may use SimpleXML which is a quick way to construct XML documents:

$o = new \SimpleXMLElement('<object/>');
$o->addAttribute('version', '42');
$o->addAttribute('type', 'object');
$o->addChild('child', 'With a value');
echo $o->asXml();

The above code will output:

<?xml version='1.0'?>
<object version='42' type='object'>
<child>With a value</child>
</object>

There is also the DOM extension:

$xml = new \DOMDocument('1.0', 'UTF-8');
$root = $xml->createElement('object');
$root->setAttribute('version', '42');
$root->setAttribute('type', 'object');
$root->appendChild(
    $xml->createElement('child', 'With a value')
);
$xml->appendChild($root);
echo $xml->saveXml();

and XMLWriter:

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('object');
$writer->writeAttribute('version', '42');
$writer->writeAttribute('type', 'object');
$writer->writeElement('child', 'With a value');
$writer->endElement();
$writer->endDocument();
$writer->flush();

All of the above requires a lot of typing, effort and boilerplate to achieve the desired result and as complexity grows you may find yourself demotivated especially when working with deep structures of data.

A good alternative is sabre/xml which wraps XMLReader and XMLWriter making the creation of XML documents a more pleasant experience:

$service = new Sabre\Xml\Service();
echo $service->write('object', function(Sabre\Xml\Writer $writer) {
    $writer->writeAttribute('version','42');
    $writer->writeAttribute('type','object');
    $writer->writeElement('child', 'With a value');
});

The library also supports serialization on objects by either using a special method xmlSerialize on an object or by providing a callback method for a specific object/class.