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>

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');
    $xml->createElement('child', 'With a value')
echo $xml->saveXml();

and XMLWriter:

$writer = new XMLWriter();
$writer->startDocument('1.0', 'UTF-8');
$writer->writeAttribute('version', '42');
$writer->writeAttribute('type', 'object');
$writer->writeElement('child', 'With a value');

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->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.