Skip to content

Core\Xml::parse

Reads a whole XML document and returns it as a tree. XML is a text format for structured data, such as a product feed or an invoice.

The tree is made of nodes of the class Core\Xml\Node. The document node is at the top, and its child is the root element. An element has a name, attributes and children. The text inside an element is a node of its own.

The document must be well-formed. A tag that is never closed, two root elements or an unknown entity throws a ParseError. The method never repairs a document, and it never loads anything from a file or from the network.

Every text you read from the tree is tainted. This means it came from outside the program.

The examples below read a small document, show what happens with a broken one, and read a stock list from a supplier.

Parameters

  • $documentstringThe document text. The five predefined entities, such as &, and numeric character references, such as A, are expanded. Any other entity reference throws a ParseError. Nothing is loaded from a file or from the network.

Return value

Returns Core\Xml\Node. The document node. Its children are the root element and any comments or processing instructions next to it. Every string you read from the tree is tainted, which means it came from outside the program. This is true even when $document was not tainted.

Errors

  • ParseErrorThe document is not well-formed. For example: a tag is never closed or is closed with a different name, there is more than one root element, an attribute is written twice, or an entity reference is not one of the predefined ones. A document type declaration also throws, and so do elements nested more than 1024 levels deep.

Examples

Read a small document

<?nvs
// Shows how to read a small XML document and print what is in it.
string $xml = '<book><title>Dune</title><author>Frank Herbert</author></book>';
// `Core\Xml::parse` returns the document node. Its only child is the root element, `book`.
Core\Xml\Node $document = Core\Xml::parse($xml);
// The text of an element is in a child of its own: a text node.
// This prints the root name, then one line for `title` and one for `author`.
foreach ($document->children() as Core\Xml\Node $book) {
echo $book->name(), "\n";
foreach ($book->children() as Core\Xml\Node $field) {
foreach ($field->children() as Core\Xml\Node $text) {
echo ' ', $field->name(), ': ', $text->text(), "\n";
}
}
}
Output
book
title: Dune
author: Frank Herbert

A broken document

<?nvs
// Shows what happens when a document is not well-formed.
// The `<price>` tag is never closed. `Core\Xml::parse` throws a `ParseError`.
// It does not try to repair the document.
try {
Core\Xml::parse('<item><name>Lamp</name><price>30</item>');
echo "parsed\n";
} catch (ParseError $error) {
echo $error->message, "\n";
}
// `&amp;` is one of the five predefined entities, so it becomes `&`. This prints `Salt & Pepper`.
Core\Xml\Node $shop = Core\Xml::parse('<shop>Salt &amp; Pepper</shop>');
foreach ($shop->children() as Core\Xml\Node $root) {
foreach ($root->children() as Core\Xml\Node $text) {
echo $text->text(), "\n";
}
}
// `&nbsp;` is not one of the five. The parser does not look it up anywhere, so this throws too.
try {
Core\Xml::parse('<shop>Salt&nbsp;Pepper</shop>');
echo "parsed\n";
} catch (ParseError $error) {
echo $error->message, "\n";
}
Output
Core\Xml::parse(): `<price>` is closed by `</item>`, and an element closes as what it opened as.
Salt & Pepper
Core\Xml::parse(): `&nbsp;` is not one of the five predefined entities, and no entity is resolved from a document type declaration, an internal subset or the network.

Read a stock list

<?nvs
// Shows how to read a stock list that a supplier sends as XML, and find what is sold out.
string $feed = "<stock>
<item sku=\"A-100\" qty=\"12\"/>
<item sku=\"B-200\" qty=\"0\"/>
<item sku=\"C-300\" qty=\"5\"/>
</stock>";
Core\Xml\Node $document = Core\Xml::parse($feed);
int $total = 0;
foreach ($document->children() as Core\Xml\Node $stock) {
foreach ($stock->children() as Core\Xml\Node $item) {
// The line breaks between the items are text nodes. This loop skips them.
if ($item->kind() != Core\Xml\Node::Kind::Element) {
continue;
}
// `attributes` returns the attributes of the element, keyed by name.
// The values are `tainted`, because they came from outside the program.
array<tainted string> $attributes = $item->attributes();
// `as ?int` converts the text to a whole number. If that is not possible, the result is `null`.
// `?? 0` then gives 0, so an unreadable quantity counts as sold out.
int $qty = ($attributes['qty'] as ?int) ?? 0;
if ($qty == 0) {
echo 'sold out: ', $attributes['sku'], "\n";
} else {
$total = $total + $qty;
}
}
}
// This prints 17: the quantities of the two items that are not sold out.
echo 'in stock: ', $total, "\n";
Output
sold out: B-200
in stock: 17