An XML library for PHP you may not hate.

If you are writing or consuming API's in PHP, chances are that you need to work with XML. In some cases you may even prefer it.

You may have started with SimpleXML and after a while switched to using the DOM after realizing SimpleXML is really not that simple if you strictly use xml namespaces everywhere.

For writing XML, you may have found that using the DOM requires far too much code, or you may simply generate your XML by echoing strings, knowing that it may not be the best idea.

sabre/xml hopes to solve your issues, by wrapping XMLReader and XMLWriter, and providing standard design patterns around:

  1. Quickly generating XML based on simple array structures,
  2. Providing a super simple XML-to-object mapping,
  3. Re-usability of parsers.

Writing XML

$xmlService = new Sabre\Xml\Service();
$xmlService->namespaceMap = ['' => 'b'];

$xmlService->write('{}book', [
    '{}title' => 'Cryptonomicon',
    '{}author' => 'Neil Stephenson',

This will create the following document:

<?xml version="1.0"?>
<b:book xmlns:b="">
 <b:author>Neil Stephenson</b:author>

You can serialize objects by implementing Sabre\Xml\XmlSerializable. This interface is designed to work identical to PHP 5.5's JsonSerializable.

Read all the details here.

Reading XML


$input = <<<XML
<article xmlns="">
    <title>Hello world</title>
    <content>Fuzzy Pickles</content>

$service = new Sabre\Xml\Service();
$service->elementMap = [
    '{}article' => 'Sabre\Xml\Element\KeyValue',


This will output something like:

    [{}title] => Hello world
    [{}content] => Fuzzy Pickles

The key in the last example, is that we tell the parser to treat the contents of the article XML node as a key-value structure.

This is optional, but by adding this hint the resulting output becomes a lot simpler.

The parser comes with a few parsing strategies for common needs, and you can easily create your own by writing deserializer classes, or just by providing a callback:

$service->elementMap = [
    '{}article' => function(Sabre\Xml\Reader $reader) {
        // Read the element's contents, and return the result here.

Read all the details here.