Library for XML manipulation

GitHub GitHub last commit CI Workflow GitHub code size in bytes GitHub Issues Total Downloads Monthly Downloads

A PHP library to work with XML documents as data: it converts them to PHP arrays and back without losing what the XML has, validates them against XSD schemas, queries them with XPath and canonicalizes them.

Features

  • Conversion: Transform between XML and PHP arrays in both directions. The elements, the attributes, the namespaces, the comments and the text are kept (see Round Trip and Fidelity).
  • Validation: Validate XML documents against XSD schemas, with the errors of libxml explained and translated.
  • Querying: XPath queries with parameters, with and without namespaces.
  • Canonicalization: Canonical XML (C14N), also in the encoding that the document declares.
  • Encoding: The document has the encoding that it declares (UTF-8 by default, ISO-8859-1 and others).
  • Special Characters: Automatic handling of XML special characters and entities.
  • Errors: Exceptions with a message that can be translated, and with the details of what failed.

Installation

composer require derafu/xml

Basic Usage

Creating XML from an Array

use Derafu\Xml\Service\XmlEncoder;

$encoder = new XmlEncoder();

// Create an array to convert to XML.
$data = [
    'root' => [
        'element1' => 'value1',
        'element2' => 'value2',
        'element3' => [
            '@attributes' => [
                'attr1' => 'attrValue',
            ],
            '@value' => 'value3',
        ],
        'repeatedElement' => ['value4', 'value5', 'value6'],
    ],
];

// Convert the array to an XML document.
$xmlDocument = $encoder->encode($data);

// Save as XML string.
$xmlString = $xmlDocument->saveXml();

// Get the XML without the XML declaration.
$xmlContent = $xmlDocument->getXml();

// Get a canonicalized version of the XML.
$c14nXml = $xmlDocument->C14N();

saveXml() gives:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <element1>value1</element1>
  <element2>value2</element2>
  <element3 attr1="attrValue">value3</element3>
  <repeatedElement>value4</repeatedElement>
  <repeatedElement>value5</repeatedElement>
  <repeatedElement>value6</repeatedElement>
</root>

Converting XML to an Array

use Derafu\Xml\Service\XmlDecoder;
use Derafu\Xml\XmlDocument;

$decoder = new XmlDecoder();

// Load an existing XML string.
$xmlContent = '<?xml version="1.0" encoding="UTF-8"?><root><element>value</element></root>';
$document = new XmlDocument();
$document->loadXml($xmlContent);

// Convert to an array.
$array = $decoder->decode($document);

// Now $array is ['root' => ['element' => 'value']].

Working with XPath

use Derafu\Xml\XPathQuery;

$xmlContent = '<?xml version="1.0"?><root><item id="1">First</item><item id="2">Second</item></root>';

// Create XPath query instance.
$query = new XPathQuery($xmlContent);

// Get a specific value.
$value = $query->getValue('/root/item[@id="2"]'); // "Second"

// Get multiple values.
$values = $query->getValues('/root/item'); // ["First", "Second"]

// Get structured array.
$array = $query->get('/root');
// Result: ['item' => ['First', 'Second']]

XML Validation

use Derafu\Xml\Exception\XmlException;
use Derafu\Xml\Service\XmlValidator;

$validator = new XmlValidator();

// Validate an XML document against a schema.
try {
    $validator->validate($xmlDocument, '/path/to/schema.xsd');
    echo "XML is valid!";
} catch (XmlException $e) {
    echo "Validation failed: " . $e->getMessage();
    $errors = $e->getErrors(); // The errors of libxml, as XmlError.
}

Advanced Usage

Working with Namespaces

The namespaces that an element declares are written in its @attributes, and the elements and attributes that use them are in them, in the document that the encoder gives:

$data = [
    'Invoice' => [
        '@attributes' => [
            'xmlns' => 'urn:example:invoice',
            'xmlns:cbc' => 'urn:example:basic',
        ],
        'cbc:ID' => 'F-1',
        'cbc:Note' => ['a', 'b'],
    ],
];

$document = $encoder->encode($data);

// Query with the namespaces, with no need to write the XML and load it again.
$namespaces = ['i' => 'urn:example:invoice', 'cbc' => 'urn:example:basic'];
$query = new XPathQuery($document, $namespaces);
$id = $query->get('//cbc:ID'); // "F-1"
$notes = $query->get('//cbc:Note'); // ["a", "b"]

Array Structure for XML Creation

When creating XML from arrays, the structure follows these conventions:

  • Simple key-value pairs become element nodes.
  • Use @attributes for node attributes and for the declarations of namespaces.
  • Use @value for the text of a node that also has attributes, child elements or comments.
  • Use @comment for comments.
  • Arrays of values create repeated nodes with the same name.

See Array Structure for all the rules.

What Is Next

On this page

Last updated on 30/10/2026 by Anonymous