---
title: "XML Project"
description: "Derafu XML"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-11-09"
last_update: "2026-11-09"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/data/xml"
---

# Derafu XML



---

## Introduction

PHP library for XML to encode, decode, validate and query documents, with XPath, canonicalization and conversion from and to arrays

# Library for XML manipulation

[![GitHub](https://img.shields.io/badge/github-derafu%2Fxml-blue?logo=github)](https://github.com/derafu/xml)
![GitHub last commit](https://img.shields.io/github/last-commit/derafu/xml/main)
![CI Workflow](https://github.com/derafu/xml/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/xml)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/xml)
![Total Downloads](https://poser.pugx.org/derafu/xml/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/xml/d/monthly)

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](round-trip)).
- **Validation**: Validate XML documents against XSD schemas, with the errors of libxml explained and translated.
- **Querying**: XPath queries with parameters, with and without namespaces, and typed reads of the document with the same methods as `ArrayReader` (see [XPath Reader](xpath-reader)).
- **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

```bash
composer require derafu/xml
```

## Basic Usage

### Creating XML from an Array

```php
use Derafu\Xml\Service\XmlEncoder;

$encoder = new XmlEncoder();

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

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

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

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

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

`saveXml()` gives:

```xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;root&gt;
  &lt;element1&gt;value1&lt;/element1&gt;
  &lt;element2&gt;value2&lt;/element2&gt;
  &lt;element3 attr1=&quot;attrValue&quot;&gt;value3&lt;/element3&gt;
  &lt;repeatedElement&gt;value4&lt;/repeatedElement&gt;
  &lt;repeatedElement&gt;value5&lt;/repeatedElement&gt;
  &lt;repeatedElement&gt;value6&lt;/repeatedElement&gt;
&lt;/root&gt;
```

### Converting XML to an Array

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

$decoder = new XmlDecoder();

// Load an existing XML string.
$xmlContent = &#039;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;root&gt;&lt;element&gt;value&lt;/element&gt;&lt;/root&gt;&#039;;
$document = new XmlDocument();
$document-&gt;loadXml($xmlContent);

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

// Now $array is [&#039;root&#039; =&gt; [&#039;element&#039; =&gt; &#039;value&#039;]].
```

### Working with XPath

```php
use Derafu\Xml\XPathQuery;

$xmlContent = &#039;&lt;?xml version=&quot;1.0&quot;?&gt;&lt;root&gt;&lt;item id=&quot;1&quot;&gt;First&lt;/item&gt;&lt;item id=&quot;2&quot;&gt;Second&lt;/item&gt;&lt;/root&gt;&#039;;

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

// Get a specific value.
$value = $query-&gt;getValue(&#039;/root/item[@id=&quot;2&quot;]&#039;); // &quot;Second&quot;

// Get multiple values.
$values = $query-&gt;getValues(&#039;/root/item&#039;); // [&quot;First&quot;, &quot;Second&quot;]

// Get structured array.
$array = $query-&gt;get(&#039;/root&#039;);
// Result: [&#039;item&#039; =&gt; [&#039;First&#039;, &#039;Second&#039;]]
```

### Reading Typed Values

```php
$reader = $document-&gt;getReader();

$reader-&gt;requireString(&#039;//seller/name&#039;);   // The text, or an error if there is none.
$reader-&gt;getAsInt(&#039;//info/number&#039;);          // The text converted to int, or null.

// One node or many is always a list, at any depth.
foreach ($reader-&gt;getReaders(&#039;//line&#039;) ?? [] as $item) {
    $item-&gt;requireString(&#039;title&#039;);
    $item-&gt;getAsNumber(&#039;qty&#039;);
}
```

See [XPath Reader](xpath-reader).

### XML Validation

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

$validator = new XmlValidator();

// Validate an XML document against a schema.
try {
    $validator-&gt;validate($xmlDocument, &#039;/path/to/schema.xsd&#039;);
    echo &quot;XML is valid!&quot;;
} catch (XmlException $e) {
    echo &quot;Validation failed: &quot; . $e-&gt;getMessage();
    $errors = $e-&gt;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:

```php
$data = [
    &#039;Invoice&#039; =&gt; [
        &#039;@attributes&#039; =&gt; [
            &#039;xmlns&#039; =&gt; &#039;urn:example:invoice&#039;,
            &#039;xmlns:cbc&#039; =&gt; &#039;urn:example:basic&#039;,
        ],
        &#039;cbc:ID&#039; =&gt; &#039;F-1&#039;,
        &#039;cbc:Note&#039; =&gt; [&#039;a&#039;, &#039;b&#039;],
    ],
];

$document = $encoder-&gt;encode($data);

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

### 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](array-structure) for all the rules.

## What Is Next

- [Array Structure](array-structure): how an XML is an array, and the other way around.
- [Round Trip and Fidelity](round-trip): what is kept when an XML becomes an array and an array becomes an XML.
- [XML Document](xml-document): the `XmlDocument` class.
- [XPath Query](xpath-query): querying documents.
- [XPath Reader](xpath-reader): reading documents with types.
- [XML Service](xml-service): encoding, decoding and validating together.
- [Exceptions](exceptions): what is thrown, when, and how to translate the messages.




---

## Array Structure

XML-Array Conversion Structure

# XML-Array Conversion Structure

The Derafu XML library uses a specific convention for representing the structure of XML documents as PHP arrays and vice versa. Understanding this structure is essential for effectively using the encoding and decoding features. For what is kept when an XML becomes an array and the array becomes an XML again, see [Round Trip and Fidelity](round-trip).

## Basic Structure

At its most basic level, an XML element with a value is represented as a key-value pair in the array:

XML:
```xml
&lt;element&gt;value&lt;/element&gt;
```

Array:
```php
[&#039;element&#039; =&gt; &#039;value&#039;]
```

## Nested Elements

Nested elements are represented as nested arrays:

XML:
```xml
&lt;parent&gt;
  &lt;child&gt;value&lt;/child&gt;
&lt;/parent&gt;
```

Array:
```php
[
    &#039;parent&#039; =&gt; [
        &#039;child&#039; =&gt; &#039;value&#039;
    ]
]
```

## Attributes

XML attributes are handled using the special `@attributes` key:

XML:
```xml
&lt;element id=&quot;123&quot; type=&quot;example&quot;&gt;value&lt;/element&gt;
```

Array:
```php
[
    &#039;element&#039; =&gt; [
        &#039;@attributes&#039; =&gt; [
            &#039;id&#039; =&gt; &#039;123&#039;,
            &#039;type&#039; =&gt; &#039;example&#039;
        ],
        &#039;@value&#039; =&gt; &#039;value&#039;
    ]
]
```

Note the use of `@value` to hold the element&#039;s text content when the element also has attributes (or child elements or comments).

## Repeated Elements

Elements with the same name are collected into arrays:

XML:
```xml
&lt;parent&gt;
  &lt;child&gt;value1&lt;/child&gt;
  &lt;child&gt;value2&lt;/child&gt;
  &lt;child&gt;value3&lt;/child&gt;
&lt;/parent&gt;
```

Array:
```php
[
    &#039;parent&#039; =&gt; [
        &#039;child&#039; =&gt; [
            &#039;value1&#039;,
            &#039;value2&#039;,
            &#039;value3&#039;
        ]
    ]
]
```

## Complex Structures

The conventions can be combined to represent complex XML structures:

XML:
```xml
&lt;root&gt;
  &lt;items&gt;
    &lt;item id=&quot;1&quot;&gt;
      &lt;name&gt;Item 1&lt;/name&gt;
      &lt;price currency=&quot;USD&quot;&gt;19.99&lt;/price&gt;
    &lt;/item&gt;
    &lt;item id=&quot;2&quot;&gt;
      &lt;name&gt;Item 2&lt;/name&gt;
      &lt;price currency=&quot;EUR&quot;&gt;29.99&lt;/price&gt;
    &lt;/item&gt;
  &lt;/items&gt;
  &lt;summary total=&quot;2&quot;&gt;Multiple items&lt;/summary&gt;
&lt;/root&gt;
```

Array:
```php
[
    &#039;root&#039; =&gt; [
        &#039;items&#039; =&gt; [
            &#039;item&#039; =&gt; [
                [
                    &#039;@attributes&#039; =&gt; [&#039;id&#039; =&gt; &#039;1&#039;],
                    &#039;name&#039; =&gt; &#039;Item 1&#039;,
                    &#039;price&#039; =&gt; [
                        &#039;@attributes&#039; =&gt; [&#039;currency&#039; =&gt; &#039;USD&#039;],
                        &#039;@value&#039; =&gt; &#039;19.99&#039;
                    ]
                ],
                [
                    &#039;@attributes&#039; =&gt; [&#039;id&#039; =&gt; &#039;2&#039;],
                    &#039;name&#039; =&gt; &#039;Item 2&#039;,
                    &#039;price&#039; =&gt; [
                        &#039;@attributes&#039; =&gt; [&#039;currency&#039; =&gt; &#039;EUR&#039;],
                        &#039;@value&#039; =&gt; &#039;29.99&#039;
                    ]
                ]
            ]
        ],
        &#039;summary&#039; =&gt; [
            &#039;@attributes&#039; =&gt; [&#039;total&#039; =&gt; &#039;2&#039;],
            &#039;@value&#039; =&gt; &#039;Multiple items&#039;
        ]
    ]
]
```

## Text

The text of an element is exactly the one that the XML has, with its spaces. The library does not trim it: what to do with the spaces is for whoever uses the value.

XML:
```xml
&lt;name&gt;  Acme Inc.  &lt;/name&gt;
```

Array:
```php
[&#039;name&#039; =&gt; &#039;  Acme Inc.  &#039;]
```

CDATA sections and entities are the text that they are (`&lt;![CDATA[x &lt; y]]&gt;` is `&#039;x &lt; y&#039;`). The spaces and the line breaks that only format the XML (the ones between elements) are not text.

When an element has child elements or comments and also text, the text is in parts, and the parts are joined with a space, without the spaces around each part (see [What the array does not keep](#what-the-array-does-not-keep)).

## Namespaces

The namespaces that an element declares are in its `@attributes`, as they are written in the XML: `xmlns` for the default one and `xmlns:prefix` for the others. They go first, sorted by name, and before the other attributes. A namespace is only where it is declared, not in the elements that inherit it.

XML:
```xml
&lt;Invoice xmlns=&quot;urn:example:invoice&quot; xmlns:cbc=&quot;urn:example:basic&quot; id=&quot;1&quot;&gt;
  &lt;cbc:ID&gt;F-1&lt;/cbc:ID&gt;
&lt;/Invoice&gt;
```

Array:
```php
[
    &#039;Invoice&#039; =&gt; [
        &#039;@attributes&#039; =&gt; [
            &#039;xmlns&#039; =&gt; &#039;urn:example:invoice&#039;,
            &#039;xmlns:cbc&#039; =&gt; &#039;urn:example:basic&#039;,
            &#039;id&#039; =&gt; &#039;1&#039;,
        ],
        &#039;cbc:ID&#039; =&gt; &#039;F-1&#039;,
    ]
]
```

The names of elements and attributes keep their prefix (`cbc:ID`, `xsi:schemaLocation`). An element that leaves the default namespace without URI has `&#039;xmlns&#039; =&gt; &#039;&#039;`. With the namespaces in the array, the XML that is created from it has the same elements in the same namespaces.

## Comments

The comments of an element are in its `@comment` key, as they are written (with their spaces): a text if there is one, a list of texts if there are several.

XML:
```xml
&lt;element&gt;
  &lt;!-- first --&gt;
  &lt;child&gt;value&lt;/child&gt;
&lt;/element&gt;
```

Array:
```php
[
    &#039;element&#039; =&gt; [
        &#039;@comment&#039; =&gt; &#039; first &#039;,
        &#039;child&#039; =&gt; &#039;value&#039;,
    ]
]
```

## Special Cases

### Empty Elements

An element without content is an empty string, whether it is written `&lt;element/&gt;` or `&lt;element&gt;&lt;/element&gt;`: it is the value of an empty element in the data model of XML.

XML:
```xml
&lt;element&gt;&lt;/element&gt;
```

Array:
```php
[&#039;element&#039; =&gt; &#039;&#039;]
```

When creating XML, the same empty string creates an empty element. An element is a `null` only when it is skipped (see below).

### Skipping Elements

When creating XML, certain values cause an element to be skipped:

```php
[
    &#039;included&#039; =&gt; &#039;This will be in the XML&#039;,
    &#039;excluded&#039; =&gt; null,       // This will be skipped.
    &#039;alsoExcluded&#039; =&gt; false,  // This will be skipped.
    &#039;emptyArraySkipped&#039; =&gt; [] // This will be skipped.
]
```

## Array to XML Encoding Rules

When using `XmlEncoder` to create XML from arrays, these rules apply:

1. Simple key-value pairs become elements with text content.
2. Nested arrays become nested elements.
3. The special key `@attributes` defines attributes for the parent element. The namespaces (`xmlns`, `xmlns:prefix`) are declared the same way.
4. The special key `@value` defines the text content of the parent element. It is written before the child elements and the comments, wherever the key is in the array.
5. The special key `@comment` adds a comment (or a list of them) to the parent element.
6. Arrays of values create multiple elements with the same name.
7. Null, false, and empty arrays are skipped (not included in the XML).
8. Empty strings (&#039;&#039;) create empty elements.
9. The array has exactly one element at its first level: it is the root element of the XML.
10. A value is written as text if it is a string, a number, a boolean or an object that can be a string. Anything else is not valid.
11. The names of elements and attributes are text. A number is the position of a value in a list, not a name.

What is not valid (a second root element, an attribute that is an array, a name that is not text, a value that can not be written as text, a text outside of an element, a comment that has two hyphens in a row or ends with a hyphen) throws an `XmlEncoderException`.

The XML has the encoding of the document that is returned: it is UTF-8 unless it is changed with `setEncoding()`.

The document that is returned has the namespaces that the array declares: its elements and its attributes are in them, as in a document that is loaded from the XML. XPath queries with namespaces and `C14N()` work in it without writing the XML and loading it again. A prefix that the array does not declare is a name without namespace.

## XML to Array Decoding Rules

When using `XmlDecoder` to convert XML to arrays, these rules apply:

1. Elements become keys in the array.
2. Text content becomes the value of the key.
3. Attributes are collected under the `@attributes` key, with the namespaces that the element declares.
4. When the element has attributes, or child elements or comments, its text content is stored under the `@value` key.
5. Multiple elements with the same name are collected into arrays.
6. Empty elements become empty strings.
7. Comments are collected under the `@comment` key.
8. Text is exactly the one of the XML, with its spaces.
9. Complex nested structures are preserved in the array hierarchy.

## What the Array Does Not Keep

An array with names as keys can not say some things that an XML can. The array that is decoded from an XML has its data, and what follows is the part that does not come back when it is encoded again:

- **The order among child elements with different names, when one of them is repeated.** The repeated elements are a list under their name.

  ```xml
  &lt;r&gt;&lt;a&gt;1&lt;/a&gt;&lt;b&gt;2&lt;/b&gt;&lt;a&gt;3&lt;/a&gt;&lt;/r&gt;   &lt;!-- [&#039;r&#039; =&gt; [&#039;a&#039; =&gt; [&#039;1&#039;, &#039;3&#039;], &#039;b&#039; =&gt; &#039;2&#039;]] --&gt;
  ```
  is encoded as `&lt;r&gt;&lt;a&gt;1&lt;/a&gt;&lt;a&gt;3&lt;/a&gt;&lt;b&gt;2&lt;/b&gt;&lt;/r&gt;`.
- **The place of the text and of the comments among the child elements.** The text that is mixed with elements or comments is joined in `@value`, and the comments of an element are together, in the place of the first one.

  ```xml
  &lt;p&gt;Hello &lt;b&gt;big&lt;/b&gt; world&lt;/p&gt;   &lt;!-- [&#039;p&#039; =&gt; [&#039;@value&#039; =&gt; &#039;Hello world&#039;, &#039;b&#039; =&gt; &#039;big&#039;]] --&gt;
  ```
  is encoded as `&lt;p&gt;Hello world&lt;b&gt;big&lt;/b&gt;&lt;/p&gt;`. It is a structure for data. It is not for documents that mix text and markup, as HTML does.
- **What is outside of the root element:** comments, processing instructions (`&lt;?xml-stylesheet ... ?&gt;`) and the document type.
- **The processing instructions inside of the elements.**
- **The declaration of the XML:** the version and `standalone`. The encoding is the one of the document (`getEncoding()` and `setEncoding()`), not of the array.
- **The entities that a document type defines.** A reference to one of them has no text in the array.
- **How the text was written:** CDATA sections, character references (`&amp;#233;`), the quotes of the attributes, `&lt;a/&gt;` or `&lt;a&gt;&lt;/a&gt;`, and the spaces that format the XML.

## Usage Examples

### Creating Complex XML

```php
use Derafu\Xml\Service\XmlEncoder;

$data = [
    &#039;invoice&#039; =&gt; [
        &#039;@attributes&#039; =&gt; [
            &#039;id&#039; =&gt; &#039;INV-2025-001&#039;,
            &#039;date&#039; =&gt; &#039;2025-03-05&#039;
        ],
        &#039;customer&#039; =&gt; [
            &#039;name&#039; =&gt; &#039;Acme Inc.&#039;,
            &#039;address&#039; =&gt; [
                &#039;street&#039; =&gt; &#039;123 Main St&#039;,
                &#039;city&#039; =&gt; &#039;Anytown&#039;,
                &#039;zipcode&#039; =&gt; &#039;12345&#039;
            ]
        ],
        &#039;items&#039; =&gt; [
            &#039;item&#039; =&gt; [
                [
                    &#039;@attributes&#039; =&gt; [&#039;sku&#039; =&gt; &#039;PROD1&#039;],
                    &#039;description&#039; =&gt; &#039;Product One&#039;,
                    &#039;quantity&#039; =&gt; &#039;2&#039;,
                    &#039;price&#039; =&gt; &#039;10.99&#039;
                ],
                [
                    &#039;@attributes&#039; =&gt; [&#039;sku&#039; =&gt; &#039;PROD2&#039;],
                    &#039;description&#039; =&gt; &#039;Product Two&#039;,
                    &#039;quantity&#039; =&gt; &#039;1&#039;,
                    &#039;price&#039; =&gt; &#039;24.99&#039;
                ]
            ]
        ],
        &#039;total&#039; =&gt; &#039;46.97&#039;
    ]
];

$encoder = new XmlEncoder();

$xmlDocument = $encoder-&gt;encode($data);
echo $xmlDocument-&gt;saveXml();
```

### Processing XML into Arrays

```php
use Derafu\Xml\Service\XmlDecoder;

$xmlString = &#039;
&lt;catalog&gt;
    &lt;book id=&quot;bk101&quot;&gt;
        &lt;author&gt;Gambardella, Matthew&lt;/author&gt;
        &lt;title&gt;XML Developer\&#039;s Guide&lt;/title&gt;
        &lt;genre&gt;Computer&lt;/genre&gt;
        &lt;price&gt;44.95&lt;/price&gt;
        &lt;publish_date&gt;2025-01-15&lt;/publish_date&gt;
    &lt;/book&gt;
    &lt;book id=&quot;bk102&quot;&gt;
        &lt;author&gt;Ralls, Kim&lt;/author&gt;
        &lt;title&gt;Midnight Rain&lt;/title&gt;
        &lt;genre&gt;Fantasy&lt;/genre&gt;
        &lt;price&gt;5.95&lt;/price&gt;
        &lt;publish_date&gt;2025-02-20&lt;/publish_date&gt;
    &lt;/book&gt;
&lt;/catalog&gt;&#039;;

$document = new \Derafu\Xml\XmlDocument();
$document-&gt;loadXml($xmlString);

$decoder = new XmlDecoder();

$array = $decoder-&gt;decode($document);

// Access data directly.
$firstBookTitle = $array[&#039;catalog&#039;][&#039;book&#039;][0][&#039;title&#039;]; // &quot;XML Developer&#039;s Guide&quot;
$secondBookPrice = $array[&#039;catalog&#039;][&#039;book&#039;][1][&#039;price&#039;]; // &quot;5.95&quot;
```

## Tips for Working with the Array Structure

1. **Plan Your Structure**: When creating XML, plan your array structure carefully to match the desired XML output.
2. **Handle Repeated Elements**: Always use numeric arrays for repeated elements with the same name.
3. **Use `@attributes` and `@value`**: Remember to use these special keys when working with elements that have both attributes and text content.
4. **Validate Your Output**: Always validate the generated XML against your schema if one exists.
5. **Check for Empty Values**: When processing arrays from XML, an empty element is an empty string (`&#039;&#039;`), not `null`.
6. **Clean the Text Where You Use It**: The text is not trimmed. If a value must have no spaces around it, trim it where it is used.




---

## Round Trip and Fidelity

What is kept when an XML becomes an array and an array becomes an XML, how it is tested and what to consider with other XML formats

# Round Trip and Fidelity

The library converts XML to arrays and arrays to XML. A round trip is to do both: an XML becomes an array, and the array becomes an XML again. This page says what the XML that comes back has, how it is tested and what to consider when the XML is not the one of a document that the library was made for.

## What Is Kept

When an XML is decoded and the array is encoded again, the XML that comes back has:

- The same elements, in the same namespaces, with the same names and prefixes.
- The same attributes, with their values and their namespaces (`xsi:schemaLocation` is not `schemaLocation`).
- The declarations of namespaces (`xmlns` and `xmlns:prefix`).
- The same text, exactly as it is: with its spaces, its line breaks and its special characters. The library does not trim it.
- The same comments inside of the document element.
- The same order of the child elements, when the elements that are repeated are together (what an XML schema asks for, in a sequence).
- The elements without content, as empty elements.

What is kept is the data of the XML, not the way it is written. The spaces that format the XML (the ones between elements), the quotes of the attributes, `&lt;a/&gt;` or `&lt;a&gt;&lt;/a&gt;` and the CDATA sections are not kept as they were written: they are the same data.

```php
$document = new XmlDocument();
$document-&gt;loadXml($xml);

$array = $decoder-&gt;decode($document);
$result = $encoder-&gt;encode($array);

// What the XML has is the same: for example, its canonical XML.
// (Without the spaces that only format the XML.)
```

## What Is Not Kept

An array of names can not say some things that an XML can: the order among child elements with different names when one of them is repeated, the place of the text and of the comments among the child elements, what is outside of the document element, the declaration of the XML and the entities that a document type defines. See [What the Array Does Not Keep](array-structure#what-the-array-does-not-keep).

## The Encoding

The encoding is not in the array: it is a property of the document that is written. Whoever uses the decoder and the encoder keeps it, with `getEncoding()` and `setEncoding()`:

```php
$document = new XmlDocument();
$document-&gt;loadXml($xml); // For example, an XML that declares ISO-8859-1.
$encoding = $document-&gt;getEncoding();

$result = $encoder-&gt;encode($decoder-&gt;decode($document));
$result-&gt;setEncoding($encoding);

$result-&gt;saveXml(); // In ISO-8859-1. What it can not write is a character reference.
```

## The Document That the Encoder Gives

The document that `XmlEncoder::encode()` gives has the namespaces that the array declares: its elements and its attributes are in them, as in a document that is loaded from the XML. So XPath queries with namespaces and `C14N()` work in it without writing the XML and loading it again.

## How It Is Tested

The test suite makes the round trip, in both directions, with the XML of its fixtures (an example of an electronic tax document and documents of the UBL standard of versions 2.1 to 2.5) and with small XML that have what other XML have: namespaces declared in several places, attributes with prefix, comments, text with spaces, CDATA, entities, unicode and ISO-8859-1.

- **XML to array to XML**: the XML that comes back has the same elements, namespaces, attributes, text, comments and order. For the fixtures it is also the same canonical XML (C14N), compared with a method that does not depend on how the comparison above is made.
- **Array to XML to array**: the array that comes back is the same.
- **Stability**: one more round trip gives the same XML.
- **Encoder**: a test with arrays made at random checks that what is encoded is decoded as it was, that what means nothing (`null`, `false` and `[]`) does not change the XML, and that a number or `true` is the same as its text.

## Using It with Other XML Formats

The library does not know the schema of the XML. It converts any XML that is data (elements, attributes and text) and keeps it, so it works with formats as UBL. What follows is what to consider when the array is used to read or to write.

### One Element or a List

An element that appears once is its value. An element that is repeated is a list. The same element can be one or the other in different documents:

```xml
&lt;Invoice&gt;&lt;InvoiceLine&gt;...&lt;/InvoiceLine&gt;&lt;/Invoice&gt;              &lt;!-- [&#039;Invoice&#039; =&gt; [&#039;InvoiceLine&#039; =&gt; [...]]] --&gt;
&lt;Invoice&gt;&lt;InvoiceLine&gt;...&lt;/InvoiceLine&gt;&lt;InvoiceLine&gt;...&lt;/InvoiceLine&gt;&lt;/Invoice&gt;
                                                               &lt;!-- [&#039;Invoice&#039; =&gt; [&#039;InvoiceLine&#039; =&gt; [[...], [...]]]] --&gt;
```

Whoever reads an array has to consider both. If the schema says that an element can be repeated, a function that always gives a list makes the code simpler:

```php
function asList(mixed $value): array
{
    return is_array($value) &amp;&amp; array_is_list($value) ? $value : [$value];
}

foreach (asList($array[&#039;Invoice&#039;][&#039;cac:InvoiceLine&#039;] ?? []) as $line) {
    // ...
}
```

### The Prefixes Are in the Keys

The names of the keys are the names of the XML, with the prefix that the document uses (`cbc:ID`). Two documents with the same data and other prefixes give arrays with other keys. To read a document that is not under your control, query it with XPath and the namespaces (see [XPath Query](xpath-query)), which do not depend on the prefixes.

### Everything Is Text

The values are text: `&#039;1.50&#039;` is not a number, and a date is not a date. A layer that knows the schema converts the types.

### The Order of the Array Is the Order of the XML

The encoder writes the elements in the order of the array. When an XML has to follow the order of a schema, the array has to have the keys in that order.




---

## XML Document

The XmlDocument class, a document with its encoding, namespaces, canonicalization, XPath queries and conversion to an array

# XmlDocument Class

`XmlDocument` is the XML document of the library. It has a PHP `DOMDocument` inside (`getDomDocument()` gives it), and adds what is needed to work with XML as data: the encoding of the document, access to its metadata, serialization that handles special characters, canonicalization, XPath queries and conversion to an array.

It is the document that `XmlEncoder::encode()` gives, the one that `XmlDecoder::decode()` and `XmlValidator::validate()` receive, and the one that the exceptions carry.

## Key Features

- Loading with the errors of libxml in the exception.
- The encoding of the document, to read and to change.
- Access to the metadata of the document: the name of the document element, its namespace and its schema.
- Serialization with the special characters and entities handled.
- Canonical XML (C14N), also in the encoding of the document.
- XPath queries with parameters.
- Conversion to a simple array, and to JSON.

## Basic Usage

### Creating a New Document

```php
use Derafu\Xml\XmlDocument;

// A document that is empty: UTF-8 and version 1.0.
$document = new XmlDocument();

// Or with another encoding (the first parameter) and version (the second one).
$document = new XmlDocument(&#039;ISO-8859-1&#039;, &#039;1.0&#039;);
```

The encoding and the version are the ones of the XML declaration when the document is saved. A document that is loaded has the ones that the XML declares.

The document does not format the XML that it saves: it only formats it if it is asked to. A document that is loaded is saved as it was loaded, with the spaces that it has between its elements, and a document that is built element by element is saved in one line. The document that `XmlService::encode()` gives is asked to format the XML (see [XmlService](xml-service)).

```php
// Save with line breaks and indentation, in the places where the document has no
// spaces between its elements. It does not matter if it is called before or after loading.
$document-&gt;setFormatOutput(true);

// Before loading: take out the spaces between elements of the XML that is loaded.
$document-&gt;setPreserveWhiteSpace(false);
```

The spaces that an XML that is loaded already has between its elements are kept, unless `setPreserveWhiteSpace(false)` is called before `loadXml()`. They are part of the content of the document, so what is saved with `saveXml()` or `getXml()` has them, with or without `setFormatOutput(true)`: the format is only added where there are no spaces.

If the XML is signed, it has to be saved as it was loaded: the spaces between its elements are part of what is signed, so a document that is saved with another format does not have a valid signature.

### Loading XML Content

```php
// Load from a string.
$xmlString = &#039;&lt;root&gt;&lt;element&gt;value&lt;/element&gt;&lt;/root&gt;&#039;;
$document-&gt;loadXml($xmlString);
```

`loadXml()` returns `true`. If the string is empty or the XML is not well formed it throws an `XmlParseException` that has the errors of libxml (see [Exceptions](exceptions)):

```php
use Derafu\Xml\Exception\XmlParseException;

try {
    $document-&gt;loadXml(&#039;&lt;root&gt;&lt;element&gt;&lt;/root&gt;&#039;);
} catch (XmlParseException $e) {
    echo $e-&gt;getMessage(); // &quot;Failed to load the XML: Line 1, column 23: Opening and ending tag mismatch: element (line 1) and root&quot;
    $errors = $e-&gt;getErrors(); // One XmlError for each error of libxml.
}
```

The loading does not convert the encoding: the document has the one that the XML declares, and `getEncoding()` says it (in upper case; `UTF-8` if the XML does not declare one). External entities are not loaded.

### Accessing Document Information

```php
// The name of the document element, with its prefix if it has one.
$name = $document-&gt;getName(); // e.g., &quot;root&quot;

// The default namespace of the document element (`xmlns`), if it has one.
$namespace = $document-&gt;getNamespace(); // e.g., &quot;urn:example:doc&quot;

// The path of the schema in xsi:schemaLocation, if there is one.
$schema = $document-&gt;getSchema(); // e.g., &quot;/path/to/schema.xsd&quot;

// The element itself, to work with it as a DOMElement.
$element = $document-&gt;getDocumentElement(); // null if there is no content.

// The same element, for who needs it: there is no null to check.
$element = $document-&gt;requireDocumentElement(); // XmlException if there is no content.
```

`requireDocumentElement()` is the one to use when the code can not go on without the element. A document without content is not a value that is not there, it is a mistake of whoever asks, so it is an `XmlException` and not a `null` that would have to be checked before using it. `getName()`, `getNamespace()` and `getSchema()` use it: they throw an `XmlException` if the document has no document element (it has no content yet), because there is nothing to ask.

For `xsi:schemaLocation=&quot;urn:example:doc /path/to/schema.xsd&quot;`, `getSchema()` gives the second part: `/path/to/schema.xsd`.

### The Encoding

```php
$encoding = $document-&gt;getEncoding(); // e.g., &quot;ISO-8859-1&quot;

// Change the encoding of the XML that is saved.
$document-&gt;setEncoding(&#039;ISO-8859-1&#039;);
```

The characters that the encoding can not write are saved as character references (`&amp;#8364;`).

### Saving and Serializing

```php
// The complete XML document with the declaration.
$xmlString = $document-&gt;saveXml();

// The XML without the declaration and without initial or final line breaks.
$xmlContent = $document-&gt;getXml();
```

Both handle the special characters of the text: `&amp;`, `&lt;` and `&gt;` are escaped, and the quotes are written as `&amp;quot;` and `&amp;apos;`.

```php
$document-&gt;loadXml(&#039;&lt;root&gt;&lt;element&gt;Text with &amp;amp; &amp;lt; &amp;gt; &quot; \&#039;&lt;/element&gt;&lt;/root&gt;&#039;);
$document-&gt;getXml();
// &lt;root&gt;
//   &lt;element&gt;Text with &amp;amp; &amp;lt; &amp;gt; &amp;quot; &amp;apos;&lt;/element&gt;
// &lt;/root&gt;
```

### Canonical XML

```php
// Canonical XML (C14N). It is always in UTF-8.
$canonical = $document-&gt;C14N();

// The same, in the encoding that the document declares (UTF-8 if it has none).
$encoded = $document-&gt;C14NEncoded();

// Only a part of the document, the first node that an XPath finds.
$part = $document-&gt;C14NEncoded(&#039;/root/section&#039;);

// The same, without the spaces between the tags.
$flat = $document-&gt;C14NEncodedFlattened();
$flatPart = $document-&gt;C14NEncodedFlattened(&#039;/root/section&#039;);
```

- `C14N()` takes the parameters of the `DOMDocument::C14N()` method of PHP (exclusive, with comments, list of nodes and namespace prefixes).
- `C14NEncoded()` and `C14NEncodedFlattened()` throw an `XmlQueryException` if the XPath finds no node.
- If the XML can not be canonicalized, `C14N()`, `C14NEncoded()`, `C14NEncodedFlattened()` and `getTopLevelSignatureC14N()` throw an `XmlException`, with what libxml said in `getErrors()`. It happens, for example, when a namespace is a relative URI (`&lt;a xmlns=&quot;relative&quot;&gt;`): libxml loads it, but the Canonical XML recommendation requires the canonicalization to fail. PHP gives `false` for it; the library does not.

To canonicalize a node, and not the whole document, `XmlHelper::canonicalize()` takes the same parameters, with the node (or the `DOMDocument`) first, and fails in the same way:

```php
use Derafu\Xml\XmlHelper;

$node = $document-&gt;getNodes(&#039;/root/section&#039;)-&gt;item(0);
$canonical = XmlHelper::canonicalize($node, exclusive: true);
```

## XPath Querying

The document has XPath queries with the namespaces ignored (see [XPath Query](xpath-query) for the details and to query with namespaces):

```php
// The result as a string, an array or null.
$result = $document-&gt;query(&#039;/root/element&#039;);

// The result as a DOMNodeList.
$nodes = $document-&gt;getNodes(&#039;/root/element&#039;);

// With parameters, quoted for you.
$result = $document-&gt;query(&#039;/root/element[@id=:id]&#039;, [&#039;id&#039; =&gt; &#039;123&#039;]);
```

To read the document with types there is `getReader()`, which gives an [`XPathReader`](xpath-reader). It takes the namespaces of the XPath expressions and where the document comes from, for the errors:

```php
$reader = $document-&gt;getReader();

$reader-&gt;requireString(&#039;/root/element&#039;);
$reader-&gt;getAsInt(&#039;/root/count&#039;);
$reader-&gt;getReaders(&#039;/root/item&#039;);

$reader = $document-&gt;getReader([&#039;cbc&#039; =&gt; &#039;urn:example:basic&#039;], &#039;invoice.xml&#039;);
```

## Array Conversion

`toArray()` is the simple version of the conversion: the value of each element by its name, without the attributes, the namespaces nor the comments. A document without content is an empty array. To have all of the XML, to create it again from the array for example, use the decoder (see [Array Structure](array-structure)).

```php
// Convert the entire document to an array.
$array = $document-&gt;toArray();

// Access a specific part using dot notation.
$value = $document-&gt;get(&#039;root.element&#039;);

// With a default value if not found.
$value = $document-&gt;get(&#039;root.missing&#039;, &#039;default value&#039;);

// The document is the array in JSON.
$json = json_encode($document);
```

## Working with Signatures

If the document has a `Signature` element as a child of its document element, you can get its canonicalized XML (C14N):

```php
// Get the canonicalized XML of the Signature that is a child of the document element.
$signatureXml = $document-&gt;getTopLevelSignatureC14N();

// Returns null if the document element has no Signature as a child.
if ($signatureXml !== null) {
    // Process signature...
}
```

The `Signature` is found by its local name, in any namespace or prefix, and only among the children of the document element. The result is the one that C14N gives (in UTF-8, whatever the encoding of the document is), with the declarations of the namespaces that are in scope in the `Signature`. For a `Signature` that is deeper in the document, for example inside an extension, use `C14NEncoded()` with its XPath.

## Serializing the Document

The document can be serialized with `serialize()` and restored with `unserialize()`: its XML is what is kept, so it comes back with the same content and encoding, and it works the same.

```php
$copy = unserialize(serialize($document));
```

## Performance Considerations

- With large XML documents, prefer XPath queries to extract the part that you need rather than converting the entire document to an array.
- The canonicalization methods do more work: use them when you need the canonical XML.
- `getXml()` is `saveXml()` without the declaration, so it does a little more work, not less.




---

## XPath Query

The XPathQuery class, XPath queries with parameters, with and without namespaces, and what each method returns

# XPathQuery Class

`XPathQuery` extracts data from XML documents using XPath expressions. It has methods for a value, for a list of values, for a structure and for the DOM nodes, parameters that are quoted for you, context nodes and support for namespaces.

## Basic Usage

```php
use Derafu\Xml\XPathQuery;

// Initialize with an XML string, an XmlDocument or a DOMDocument.
$query = new XPathQuery($xmlString);

// Get a single value.
$value = $query-&gt;getValue(&#039;/root/element&#039;);

// Get multiple values.
$values = $query-&gt;getValues(&#039;/root/items/item&#039;);

// Get DOM nodes.
$nodes = $query-&gt;getNodes(&#039;/root/items/item&#039;);

// Get structured data.
$data = $query-&gt;get(&#039;/root&#039;);
```

An XML string that is not well formed throws an `XmlParseException` when the query is created. A query that fails throws an `XmlQueryException` (see [Exceptions](exceptions)).

## What Each Method Returns

| Method | Returns |
|---|---|
| `getValue($query)` | The value of the first node, as a string, or `null` if there is none. |
| `getValues($query)` | A list with the value of each node. A node without value is `null`. |
| `getNodes($query)` | A `DOMNodeList` with the nodes. |
| `get($query)` | The structure of what the query finds, as the next section says. |

### The Structure That `get()` Returns

1. `null` if no node is found.
2. A string if a node that has only text is found (an element without content is an empty string; an attribute is its value).
3. An array if the node has child elements: the value of each child by its name, and a list for the elements that are repeated.
4. A list of those, if several nodes are found.

It is the simple structure of the document: the attributes, the namespaces and the comments are not in it. For all of the XML use the decoder (see [Array Structure](array-structure)).

For this XML:

```xml
&lt;root&gt;
  &lt;person&gt;
    &lt;name&gt;John&lt;/name&gt;
    &lt;age&gt;30&lt;/age&gt;
  &lt;/person&gt;
  &lt;person&gt;
    &lt;name&gt;Jane&lt;/name&gt;
    &lt;age&gt;25&lt;/age&gt;
  &lt;/person&gt;
&lt;/root&gt;
```

The query `$query-&gt;get(&#039;/root/person&#039;)` returns:

```php
[
    [&#039;name&#039; =&gt; &#039;John&#039;, &#039;age&#039; =&gt; &#039;30&#039;],
    [&#039;name&#039; =&gt; &#039;Jane&#039;, &#039;age&#039; =&gt; &#039;25&#039;],
]
```

And `$query-&gt;get(&#039;/root/person[1]/name&#039;)` returns `&#039;John&#039;`.

## Parameterized Queries

The values that go in a query are given as parameters: in the query the parameter is written `:name`, and in the array of parameters it is `name`. They are quoted for you, also when they have quotes:

```php
$result = $query-&gt;get(&#039;//item[@id=:id and @type=:type]&#039;, [
    &#039;id&#039; =&gt; &#039;123&#039;,
    &#039;type&#039; =&gt; &#039;product&#039;,
]);

$params = [&#039;complex&#039; =&gt; &#039;Value with &quot;double&quot; and \&#039;single\&#039; quotes&#039;];
$result = $query-&gt;get(&#039;//element[text()=:complex]&#039;, $params);
```

## Context Nodes

`get()`, `getValue()`, `getValues()` and `getNodes()` take a context node as the last parameter, to query from it:

```php
// Get a context node.
$contextNode = $query-&gt;getNodes(&#039;//section&#039;)-&gt;item(0);

// Query within that context.
$result = $query-&gt;get(&#039;./item&#039;, [], $contextNode);
```

## Working with Namespaces

By default the namespaces are ignored: the names in the query match the elements by their local name, whatever their namespace and prefix.

```php
$xml = &#039;&lt;r xmlns=&quot;urn:d&quot; xmlns:p=&quot;urn:p&quot;&gt;&lt;p:a&gt;1&lt;/p:a&gt;&lt;b&gt;2&lt;/b&gt;&lt;/r&gt;&#039;;

$query = new XPathQuery($xml);
$query-&gt;get(&#039;//a&#039;); // &quot;1&quot;: the element p:a, found by its name.
$query-&gt;get(&#039;//b&#039;); // &quot;2&quot;
```

Only the names of the elements are read this way. The rest of the expression is what XPath says: the functions and the node tests (`count()`, `text()`), the axes (`following-sibling::`), the attributes, the operators (`and`, `or`, `div`, `mod`) and the string literals.

```php
$xml = &#039;&lt;r xmlns=&quot;urn:d&quot;&gt;&lt;a&gt;1&lt;/a&gt;&lt;b-c id=&quot;5&quot;&gt;2&lt;/b-c&gt;&lt;/r&gt;&#039;;

$query = new XPathQuery($xml);
$query-&gt;get(&#039;//a/text()&#039;);                // &quot;1&quot;
$query-&gt;get(&#039;//b-c[@id=&quot;5&quot;]&#039;);            // &quot;2&quot;: a name can have a hyphen.
$query-&gt;get(&#039;//a/following-sibling::b-c&#039;); // &quot;2&quot;
```

With the namespaces of the query as the second parameter they are used as the XPath says: the names have the prefix of the namespace that they are in.

```php
$namespaces = [&#039;d&#039; =&gt; &#039;urn:d&#039;, &#039;p&#039; =&gt; &#039;urn:p&#039;];
$query = new XPathQuery($xml, $namespaces);

$query-&gt;get(&#039;//p:a&#039;); // &quot;1&quot;
$query-&gt;get(&#039;//d:b&#039;); // &quot;2&quot;
$query-&gt;get(&#039;//b&#039;);   // null: b is in the namespace urn:d, it is not a name without namespace.
```

The prefixes are the ones that you give, not the ones that the document uses: they can be different. It is the way to query a document whose prefixes you do not control.

Without registering the namespaces a name with a prefix (`//p:a`) is not valid.

## Querying an XmlDocument

An `XmlDocument` can be given instead of a string. Also the one that the encoder gives:

```php
$document = $encoder-&gt;encode($data);

$query = new XPathQuery($document, [&#039;cbc&#039; =&gt; &#039;urn:example:basic&#039;]);
$query-&gt;get(&#039;//cbc:ID&#039;);
```

`XmlDocument::query()` and `getNodes()` use `XPathQuery` without namespaces, and they read the document as it was loaded last.

An `XPathQuery` reads the content that the document had when the query was created: if the XML is loaded again in the document, create a new query. To read a document with types, and as it is each time it is asked, see [XPath Reader](xpath-reader).

## Error Handling

```php
use Derafu\Xml\Exception\XmlQueryException;

try {
    $result = $query-&gt;get(&#039;//invalid[xpath&#039;);
} catch (XmlQueryException $e) {
    echo $e-&gt;getMessage();
    // An error occurred while executing the XPath expression: ... Invalid predicate.
}
```




---

## XPath Reader

The XPathReader class, typed reads of an XML document selected by XPath, with the same methods as ArrayReader

# XPathReader Class

`XPathReader` reads an XML document with types. It is to an XML document what [`ArrayReader`](https://www.derafu.dev/docs/data/array/readers) is to an array: the same methods, with the same contract, and an XPath expression where `ArrayReader` takes a key.

```php
use Derafu\Xml\XmlDocument;

$document = new XmlDocument();
$document-&gt;loadXml(&lt;&lt;&lt;XML
&lt;order&gt;
    &lt;header&gt;
        &lt;info&gt;
            &lt;docType&gt;33&lt;/docType&gt;
            &lt;number&gt;0021&lt;/number&gt;
            &lt;issued&gt;2025-03-07&lt;/issued&gt;
        &lt;/info&gt;
        &lt;seller&gt;
            &lt;taxId&gt;TAX-1&lt;/taxId&gt;
            &lt;name&gt;Seller name&lt;/name&gt;
            &lt;phone&gt;111&lt;/phone&gt;
            &lt;phone&gt;222&lt;/phone&gt;
        &lt;/seller&gt;
    &lt;/header&gt;
    &lt;line&gt;
        &lt;title&gt;Item A&lt;/title&gt;
        &lt;qty&gt;2&lt;/qty&gt;
        &lt;code&gt;&lt;value&gt;111&lt;/value&gt;&lt;/code&gt;
        &lt;code&gt;&lt;value&gt;222&lt;/value&gt;&lt;/code&gt;
    &lt;/line&gt;
    &lt;line&gt;
        &lt;title&gt;Item B&lt;/title&gt;
        &lt;qty&gt;3&lt;/qty&gt;
        &lt;code&gt;&lt;value&gt;333&lt;/value&gt;&lt;/code&gt;
    &lt;/line&gt;
    &lt;shipping&gt;
        &lt;customs/&gt;
    &lt;/shipping&gt;
&lt;/order&gt;
XML);

$reader = $document-&gt;getReader();

$reader-&gt;requireString(&#039;//seller/name&#039;);   // &#039;Seller name&#039;
$reader-&gt;getAsInt(&#039;//info/number&#039;);          // 21
$reader-&gt;getString(&#039;//info/number&#039;);         // &#039;0021&#039;
$reader-&gt;getString(&#039;//seller/branch&#039;);     // null: no node matches.
$reader-&gt;requireString(&#039;//seller/branch&#039;); // throws XmlQueryException.
```

## Getting a Reader

```php
use Derafu\Xml\XPathReader;

$reader = $document-&gt;getReader();
$reader = XPathReader::fromDocument($document);

// With the namespaces that the XPath expressions use, and where the document
// comes from, which the errors say.
$reader = $document-&gt;getReader([&#039;cbc&#039; =&gt; &#039;urn:example:basic&#039;], &#039;invoice.xml&#039;);
```

Without namespaces they are ignored, as in `XmlDocument::query()`: the names in the XPath match the elements by their local name. With them the XPath is used as it is written, with the prefixes that you give (see [XPath Query](xpath-query#working-with-namespaces)).

The reader reads the document each time it is asked, so it sees the changes that are made to the document and the XML that is loaded in it again.

## Strict and Converting Reads

The text of an XML node is always a string. The reader has two kinds of reads, as `ArrayReader` does:

- `getXxx()` is strict: it returns `null` when no node matches, and throws when what it finds is not of the type. `requireXxx()` is the same, and it also throws when no node matches.
- `getAsXxx()` converts the text to the type, with the conversions of [Value](https://www.derafu.dev/docs/data/value/casting): `&#039;0021&#039;` is `21`. `requireAsXxx()` throws when no node matches.

There are no strict getters for `int`, `float`, `number` or `bool`: they could never succeed with the text of a node.

| Method | Returns |
|---|---|
| `getString()`, `requireString()` | `string`, the text as it is |
| `getNonEmptyString()`, `requireNonEmptyString()` | `non-empty-string`; an empty element throws |
| `getAsString()`, `requireAsString()` | `string` |
| `getAsInt()`, `requireAsInt()` | `int` |
| `getAsFloat()`, `requireAsFloat()` | `float` |
| `getAsNumber()`, `requireAsNumber()` | `int` or `float`, as the text is |
| `getAsBool()`, `requireAsBool()` | `bool`; a text that is not a boolean throws |
| `getDateTime()`, `requireDateTime()` | `DateTimeInterface`, from a text that PHP reads as a date (see `ValueType::dateTime()`); another text throws |
| `getEnum()`, `requireEnum()` | the case of a backed enum with that value; another text throws |

```php
$reader-&gt;getString(&#039;//info/number&#039;);       // &#039;0021&#039;: the text, as it is.
$reader-&gt;getAsInt(&#039;//info/number&#039;);        // 21
$reader-&gt;getAsFloat(&#039;//info/number&#039;);      // 21.0
$reader-&gt;getAsBool(&#039;//info/number&#039;);       // throws: it is not a boolean text.
```

The `getXxx()` methods take a default when no node matches, as `ArrayReader` does:

```php
$reader-&gt;getString(&#039;//seller/branch&#039;, &#039;Main&#039;); // &#039;Main&#039;
$reader-&gt;getAsInt(&#039;//seller/branchCode&#039;, 0);           // 0
```

### Any Type

`get()` and `require()` read what the XPath finds as any `ValueType`. All the other methods are made with them:

```php
use Derafu\Value\ValueType;

$reader-&gt;require(&#039;//info/number&#039;, ValueType::toInt());    // 21
$reader-&gt;get(&#039;//info/issued&#039;, ValueType::dateTime());   // DateTimeImmutable
```

What they find is what `XPathQuery::get()` gives: `null` if no node matches, a string for a node with only text, an array for a node with child elements, and a list if several nodes match.

### Presence

```php
$reader-&gt;hasKey(&#039;//seller/name&#039;);  // true: a node matches.
$reader-&gt;hasValue(&#039;//seller/name&#039;); // true: a node matches and it has a value.
```

## One Node or Many

XML has no list type: an element that appears once is a value, and an element that appears several times is a list. The reads of a list take what the XPath finds, one node or many, as a list:

```php
$reader-&gt;getStringList(&#039;//seller/phone&#039;);  // [&#039;111&#039;, &#039;222&#039;]
$reader-&gt;getListOf(&#039;//line/qty&#039;, ValueType::toInt()); // [2, 3]
$reader-&gt;getList(&#039;//header&#039;);             // [[&#039;info&#039; =&gt; [...], &#039;seller&#039; =&gt; [...]]]: one node, a list of one.
```

| Method | Returns |
|---|---|
| `getList()`, `requireList()` | `list&lt;mixed&gt;` |
| `getStringList()`, `requireStringList()` | `list&lt;string&gt;` |
| `getListOf($xpath, $type)`, `requireListOf()` | `list&lt;T&gt;`, each item is of the type |

A list of nothing is `null` with `getXxx()` and an exception with `requireXxx()`, as in `ArrayReader`. `$reader-&gt;getStringList(&#039;//seller/phone&#039;) ?? []` is the list that is empty when there is none.

## Structures

A node with child elements is a structure, an array. An element without text and without children is an empty structure: it is `[]` in the methods that read a structure.

```php
$reader-&gt;getMap(&#039;//seller&#039;);           // [&#039;taxId&#039; =&gt; &#039;TAX-1&#039;, &#039;name&#039; =&gt; &#039;Seller name&#039;, &#039;phone&#039; =&gt; [&#039;111&#039;, &#039;222&#039;]]
$reader-&gt;getMap(&#039;//customs&#039;);           // []: an empty element.
$reader-&gt;getMap(&#039;//seller/name&#039;);    // throws: it has text, it is not a structure.
```

| Method | Returns |
|---|---|
| `getArray()`, `requireArray()` | `array` |
| `getMap()`, `requireMap()` | `array&lt;string, mixed&gt;` |
| `getMapOf($xpath, $type)`, `requireMapOf()` | `array&lt;string, T&gt;` |
| `getArrayOf($xpath, $type)`, `requireArrayOf()` | `array&lt;array-key, T&gt;` |

An empty element is also `[]` when it is an item of a list of structures or a value of a structure of structures, which is when the type of the items is `map`, `array` or `list`:

```php
// &lt;r&gt;&lt;item/&gt;&lt;item&gt;&lt;a&gt;1&lt;/a&gt;&lt;/item&gt;&lt;/r&gt;
$reader-&gt;getListOf(&#039;//item&#039;, ValueType::map());  // [[], [&#039;a&#039; =&gt; &#039;1&#039;]]

// &lt;r&gt;&lt;text/&gt;&lt;text&gt;x&lt;/text&gt;&lt;/r&gt;
$reader-&gt;getListOf(&#039;//text&#039;, ValueType::string()); // [&#039;&#039;, &#039;x&#039;]: the items are not structures.
```

`get()` and `require()` give an empty element as it is in `XPathQuery`, an empty string.

## Readers of a Node

`getReader()` gives a reader of one node, and `getReaders()` a reader of each node that the XPath matches, one node or many. They are readers like the one that makes them, scoped to the node: all that is read from them is read in the same way, at any depth.

```php
foreach ($reader-&gt;getReaders(&#039;//line&#039;) ?? [] as $item) {
    $item-&gt;requireString(&#039;title&#039;);           // &#039;Item A&#039;, then &#039;Item B&#039;.
    $item-&gt;getAsInt(&#039;qty&#039;);                // 2, then 3.

    // Inside of a node, one element or many.
    foreach ($item-&gt;getReaders(&#039;code&#039;) ?? [] as $codigo) {
        $codigo-&gt;requireString(&#039;value&#039;);   // &#039;111&#039;, &#039;222&#039;, then &#039;333&#039;.
    }
}

$seller = $reader-&gt;requireReader(&#039;//seller&#039;);
$seller-&gt;requireString(&#039;taxId&#039;);
```

| Method | Returns |
|---|---|
| `getReader()`, `requireReader()` | `XPathReader`; it throws if the XPath matches more than one node |
| `getReaders()`, `requireReaders()` | `list&lt;XPathReader&gt;` |

The reader of an empty element is a reader of `[]`: everything that it reads is absent. A node that is not an element or that has text is not a structure and has no reader.

An optional `ValueType` checks the structure of the node: `$reader-&gt;getReader(&#039;//seller&#039;, ValueType::map())`.

### Relative XPath

The XPath expressions of a reader of a node are relative to it: `title` and `./title` are its child. A `//` still starts at the root of the document:

```php
$item-&gt;requireString(&#039;//seller/name&#039;); // &#039;Seller name&#039;: from the root.
```

## The Whole Structure

The operations on the whole structure of the document, or of the node of a reader, are the ones of `ArrayReader`:

```php
$reader-&gt;toArray();                       // What XmlDocument::toArray() gives.
$reader-&gt;toMap();                         // The structure, that must have only string keys.
$reader-&gt;to(ValueType::array());          // Checks it against a type.
$seller-&gt;assertOnlyKeys(&#039;taxId&#039;, &#039;name&#039;, &#039;phone&#039;); // An error for another child.
```

Their errors are `XmlQueryException` like the ones of the reads, with the XPath of the structure: `/` for the whole document, and for an element that is not allowed the XPath of the element (`//seller/branch`).

## Errors

Every error is an `XmlQueryException` (see [Exceptions](exceptions)) that has the XPath expression, the document and, when it was a type that failed, the cause:

```php
use Derafu\Xml\Exception\XmlQueryException;

try {
    $reader-&gt;requireString(&#039;//seller/branch&#039;);
} catch (XmlQueryException $e) {
    $e-&gt;getMessage();         // The XPath &quot;//seller/branch&quot; is required: it matched no node.
    $e-&gt;getXpathExpression(); // &#039;//seller/branch&#039;
    $e-&gt;getXmlDocument();     // The document.
}
```

The errors of a reader of a node have the full XPath of the node: `//seller/missing`, or `(//line)[2]/title` for the second of several. With a source, the message says it: `The XPath &quot;//seller/branch&quot; of invoice.xml is required: it matched no node.`

An XPath expression that is not valid throws the `XmlQueryException` of `XPathQuery`.

## Methods

| Kind | Methods |
|---|---|
| Presence | `hasKey()`, `hasValue()` |
| Any type | `get()`, `require()` |
| Text and values | `getString()`, `getNonEmptyString()`, `getDateTime()`, `getEnum()` and their `require` pairs |
| Conversions | `getAsString()`, `getAsInt()`, `getAsFloat()`, `getAsNumber()`, `getAsBool()` and their `requireAs` pairs |
| Structures | `getArray()`, `getMap()`, `getMapOf()`, `getArrayOf()` and their `require` pairs |
| Lists | `getList()`, `getStringList()`, `getListOf()` and their `require` pairs |
| Readers of a node | `getReader()`, `getReaders()` and their `require` pairs |
| The whole structure | `toArray()`, `to()`, `toMap()`, `toList()`, `assertOnlyKeys()` |




---

## XML Service

The XmlService class and its encoder, decoder and validator to convert and validate XML documents

# XmlService Class

`XmlService` is the entry point of the library: it encodes, decodes and validates XML documents in one place. It gives the work to three components, that can also be used alone.

## Service Structure

1. **XmlEncoder**: Converts PHP arrays to XML documents.
2. **XmlDecoder**: Converts XML documents to PHP arrays.
3. **XmlValidator**: Validates XML documents against XSD schemas.

`XmlServiceInterface` is the three interfaces together (`XmlEncoderInterface`, `XmlDecoderInterface` and `XmlValidatorInterface`).

## Basic Usage

```php
use Derafu\Xml\Service\XmlEncoder;
use Derafu\Xml\Service\XmlDecoder;
use Derafu\Xml\Service\XmlValidator;
use Derafu\Xml\Service\XmlService;

// Initialize the components.
$encoder = new XmlEncoder();
$decoder = new XmlDecoder();
$validator = new XmlValidator();

// Create the service.
$xmlService = new XmlService($encoder, $decoder, $validator);
```

In an application with the Symfony container, `resources/config/xml-services.yaml` of the library registers the interfaces with their classes.

## Encoding (Array to XML)

The `encode()` method converts a PHP array to an XML document (see [Array Structure](array-structure)):

```php
$data = [
    &#039;invoice&#039; =&gt; [
        &#039;@attributes&#039; =&gt; [
            &#039;id&#039; =&gt; &#039;12345&#039;,
            &#039;date&#039; =&gt; &#039;2025-03-05&#039;
        ],
        &#039;client&#039; =&gt; [
            &#039;name&#039; =&gt; &#039;Acme Corporation&#039;,
            &#039;tax_id&#039; =&gt; &#039;123456789&#039;
        ],
        &#039;items&#039; =&gt; [
            &#039;item&#039; =&gt; [
                [
                    &#039;@attributes&#039; =&gt; [&#039;id&#039; =&gt; &#039;1&#039;],
                    &#039;description&#039; =&gt; &#039;Product A&#039;,
                    &#039;quantity&#039; =&gt; &#039;2&#039;,
                    &#039;price&#039; =&gt; &#039;19.99&#039;
                ],
                [
                    &#039;@attributes&#039; =&gt; [&#039;id&#039; =&gt; &#039;2&#039;],
                    &#039;description&#039; =&gt; &#039;Product B&#039;,
                    &#039;quantity&#039; =&gt; &#039;1&#039;,
                    &#039;price&#039; =&gt; &#039;29.99&#039;
                ]
            ]
        ],
        &#039;total&#039; =&gt; &#039;69.97&#039;
    ]
];

$xmlDocument = $xmlService-&gt;encode($data);
```

`$xmlDocument-&gt;saveXml()` gives:

```xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;invoice id=&quot;12345&quot; date=&quot;2025-03-05&quot;&gt;
  &lt;client&gt;
    &lt;name&gt;Acme Corporation&lt;/name&gt;
    &lt;tax_id&gt;123456789&lt;/tax_id&gt;
  &lt;/client&gt;
  &lt;items&gt;
    &lt;item id=&quot;1&quot;&gt;
      &lt;description&gt;Product A&lt;/description&gt;
      &lt;quantity&gt;2&lt;/quantity&gt;
      &lt;price&gt;19.99&lt;/price&gt;
    &lt;/item&gt;
    &lt;item id=&quot;2&quot;&gt;
      &lt;description&gt;Product B&lt;/description&gt;
      &lt;quantity&gt;1&lt;/quantity&gt;
      &lt;price&gt;29.99&lt;/price&gt;
    &lt;/item&gt;
  &lt;/items&gt;
  &lt;total&gt;69.97&lt;/total&gt;
&lt;/invoice&gt;
```

The encoding of the XML is UTF-8. To have another one: `$xmlDocument-&gt;setEncoding(&#039;ISO-8859-1&#039;)`.

The document that `encode()` gives is asked to format the XML that it saves, as in the example (an XML that is built from an array has no spaces between its elements). To save it in one line: `$xmlDocument-&gt;setFormatOutput(false)`.

An array that can not be an XML throws an `XmlEncoderException` (see [Exceptions](exceptions)).

### Using Namespaces

The namespaces are declared in the `@attributes` of the element, with `xmlns` for the default one and `xmlns:prefix` for the others. The names of the elements have the prefix:

```php
$data = [
    &#039;inv:invoice&#039; =&gt; [
        &#039;@attributes&#039; =&gt; [
            &#039;xmlns:inv&#039; =&gt; &#039;http://example.com/invoice&#039;,
            &#039;id&#039; =&gt; &#039;12345&#039;,
        ],
        &#039;inv:client&#039; =&gt; &#039;Acme Corporation&#039;,
    ],
];

$xmlDocument = $xmlService-&gt;encode($data);
```

This generates:

```xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;inv:invoice xmlns:inv=&quot;http://example.com/invoice&quot; id=&quot;12345&quot;&gt;
  &lt;inv:client&gt;Acme Corporation&lt;/inv:client&gt;
&lt;/inv:invoice&gt;
```

## Decoding (XML to Array)

The `decode()` method converts an XML document to a PHP array:

```php
// Assuming $xmlDocument is a Derafu\Xml\XmlDocument instance.
$array = $xmlService-&gt;decode($xmlDocument);

// Or starting from a DOMElement of the document.
$element = $xmlDocument-&gt;getDocumentElement();
$array = $xmlService-&gt;decode($element);
```

A document without document element is an empty array.

The array has what the XML has: attributes and the namespaces that the elements declare in `@attributes`, comments in `@comment`, and text exactly as it is. See [Array Structure](array-structure) and [Round Trip and Fidelity](round-trip).

### Handling Repeated Elements

Elements with the same name are collected into a list:

```xml
&lt;root&gt;
  &lt;item&gt;Value 1&lt;/item&gt;
  &lt;item&gt;Value 2&lt;/item&gt;
  &lt;item&gt;Value 3&lt;/item&gt;
&lt;/root&gt;
```

Becomes:

```php
[
    &#039;root&#039; =&gt; [
        &#039;item&#039; =&gt; [
            &#039;Value 1&#039;,
            &#039;Value 2&#039;,
            &#039;Value 3&#039;
        ]
    ]
]
```

An element that appears once is its value, not a list of one.

## Validation

The `validate()` method checks an XML document against an XSD schema:

```php
use Derafu\Xml\Exception\XmlException;

try {
    $xmlService-&gt;validate($xmlDocument, &#039;/path/to/schema.xsd&#039;);
    echo &quot;XML is valid!&quot;;
} catch (XmlException $e) {
    echo &quot;Validation failed: &quot; . $e-&gt;getMessage();

    // The errors of libxml, as XmlError.
    foreach ($e-&gt;getErrors() as $error) {
        echo &quot;- $error\n&quot;;
    }

    // The document that was validated.
    $document = $e-&gt;getXmlDocument();
}
```

The message has all the errors:

```
The XML validation failed using the schema schema.xsd: Line 1, column 0: Element &#039;wrong&#039;: No matching global declaration available for the validation root.
```

The errors are explained and translated from their code (see [Exceptions](exceptions#the-errors-of-libxml)), and the namespace of the names, that libxml writes between braces (`{urn:example}`), is taken out.

### Schema Auto-Detection

If the XML document has an `xsi:schemaLocation` attribute, the schema path can be omitted: the schema is the path that comes after the namespace.

```php
// XML with xsi:schemaLocation=&quot;http://example.com/ns /path/to/schema.xsd&quot;
try {
    $xmlService-&gt;validate($xmlDocument); // Will use /path/to/schema.xsd
} catch (XmlException $e) {
    // Handle validation error.
}
```

The path has to be one of a file that exists. If the document does not have `xsi:schemaLocation`, or the path does not exist, an `XmlException` is thrown.

## Integration Example

This example shows a typical workflow:

```php
// Initialize the service.
$xmlService = new XmlService(new XmlEncoder(), new XmlDecoder(), new XmlValidator());

// Create XML from array.
$data = [&#039;root&#039; =&gt; [&#039;element&#039; =&gt; &#039;value&#039;]];
$xmlDocument = $xmlService-&gt;encode($data);

// Save to a file.
file_put_contents(&#039;document.xml&#039;, $xmlDocument-&gt;saveXml());

// Load from a file.
$loadedXml = new \Derafu\Xml\XmlDocument();
$loadedXml-&gt;loadXml(file_get_contents(&#039;document.xml&#039;));

try {
    // Validate.
    $xmlService-&gt;validate($loadedXml, &#039;/path/to/schema.xsd&#039;);

    // Convert back to array.
    $array = $xmlService-&gt;decode($loadedXml);

    // Process the data.
    // ...

} catch (\Derafu\Xml\Exception\XmlException $e) {
    // Handle validation errors.
}
```




---

## Exceptions

The exceptions of the XML library, when they are thrown, the details that they have and how to translate their messages

# Exceptions

All the exceptions of the library extend `Derafu\Xml\Exception\XmlException`, so one `catch` takes all of them.

## The Exceptions

| Exception | When it is thrown |
|---|---|
| `XmlException` | A document without document element where it is needed, a validation that fails, a schema that is not found, and failures of PHP while the XML is generated (serializing, canonicalizing). |
| `XmlParseException` | `loadXml()` with an XML that is empty or is not well formed. |
| `XmlQueryException` | An XPath expression that is not valid or that fails, a read of [`XPathReader`](xpath-reader) that finds no node or finds a value that is not of the type, and `C14NEncoded()` with an XPath that finds no node. |
| `XmlEncoderException` | An array that can not be converted to XML. |

`XmlParseException`, `XmlQueryException` and `XmlEncoderException` extend `XmlException`.

### Array that Can Not Be Converted

`XmlEncoder::encode()` throws `XmlEncoderException` when:

- The array has more than one element at its first level, or a list: an XML has only one root element.
- A name of an element or attribute is not text (a number is the position of a value in a list, not a name).
- A value is not text: a string, a number, a boolean or an object that can be a string are valid. An array can not be the value of an attribute.
- `@value` is at the first level of the array, outside of any element.
- A comment has two hyphens in a row or ends with a hyphen.

## What the Exceptions Have

```php
use Derafu\Xml\Exception\XmlException;

try {
    $document-&gt;loadXml(&#039;&lt;r&gt;&lt;a&gt;&lt;/r&gt;&#039;);
} catch (XmlException $e) {
    $e-&gt;getMessage();     // &quot;Failed to load the XML: Line 1, column 11: Opening and ending tag mismatch: a (line 1) and r&quot;
    $e-&gt;getErrors();      // A list of XmlError, one for each error of libxml.
    $e-&gt;getXmlDocument(); // The document that caused the exception, if there is one.
}
```

- `getErrors()` gives the errors that explain the exception, as a list of `XmlError`: the ones of libxml when an XML is loaded, canonicalized or validated. It is an empty list if there are none.
- `getXmlDocument()` gives the `XmlDocument` that caused the exception, or `null`.
- `XmlQueryException` also has `getXpathExpression()`: the XPath that was asked. In a read of `XPathReader` it is the full XPath of the node, and the exception also has the cause when it was a type that failed (`getPrevious()`).

When there are errors, the message has them, so the message says what failed. When an XML is loaded or canonicalized the message has the error that caused the failure: the first fatal one (the others that libxml reports after it are consequences of it), or else the first error. When an XML is validated the message has all the errors:

```
The XML validation failed using the schema schema.xsd: Line 1, column 0: Element &#039;wrong&#039;: No matching global declaration available for the validation root.
```

## The Errors of libxml

An `XmlError` is an error that libxml found, with its data:

```php
foreach ($e-&gt;getErrors() as $error) {
    $error-&gt;level;   // XmlErrorLevel::Warning, XmlErrorLevel::Error or XmlErrorLevel::Fatal.
    $error-&gt;code;    // The code of the error in libxml, for example 76.
    $error-&gt;line;    // The line of the XML, 0 if it has none.
    $error-&gt;column;  // The column of the line, 0 if it has none.
    $error-&gt;message; // The original text of libxml.
    (string) $error; // &quot;Line 1, column 11: Opening and ending tag mismatch: a (line 1) and r&quot;
}
```

An `XmlError` is translatable like the exceptions: `$error-&gt;trans($translator)` says it in the language of the translator. The text is made from the code of the error: the library has the translation of each error of libxml that it can say when it loads, canonicalizes or validates an XML (parsing, namespaces and XSD schemas). An error that is not known, or that libxml says in a way that is not known, keeps the original text of libxml. A warning says so (`Warning, line 1, column 4: ...`), and an error without a line (for example one of the schema) has no location.

The names of elements and attributes are shown without the namespace that libxml writes between braces (`{urn:example}`). The errors are in the exception for whoever wants to show them in another way: the code identifies the error better than its text.

## Translating the Messages

The exceptions are translatable (they are the ones of the `derafu/translation` library): their messages are in English, and the library has their translation to Spanish. To have the message in another language, use `trans()` with a translator:

```php
use Derafu\Translation\TranslatorFactory;
use Derafu\Xml\Translation\XmlTranslationResourceProvider;

$translator = TranslatorFactory::create(&#039;es&#039;, [], [new XmlTranslationResourceProvider()]);

try {
    $document-&gt;loadXml(&#039;&#039;);
} catch (XmlException $e) {
    echo $e-&gt;getMessage();            // &quot;The XML content that you want to load is empty.&quot;
    echo $e-&gt;trans($translator);      // &quot;El contenido XML que se quiere cargar está vacío.&quot;
}
```

The translations are in `resources/translations/errors+intl-icu.es.php`. In an application with the Symfony container, `resources/config/xml-services.yaml` of the library registers `XmlTranslationResourceProvider` with the tag `derafu_translation.resource_provider`, so its translations are loaded with the ones of the other libraries.

The errors in `getErrors()` are translated too: see [The Errors of libxml](#the-errors-of-libxml).





---
Last updated on 09/11/2026
#php
