XML with SimpleXML and DOM
PHP reads XML with two tools in the standard library: SimpleXML turns a document into an object, and DOMDocument edits one node by node. Every example below parses a document built inside the program, so the output on this page is the output of the run.
Read with SimpleXML
SimpleXML turns an XML document into an object that you can read with normal property access. It is the fastest way to read small config files and API responses.
Load from a string with simplexml_load_string or from a file with simplexml_load_file. Check for false before reading nodes.
<?php $xml = simplexml_load_string("<root><item>Ada</item></root>"); echo $xml->item, PHP_EOL; var_dump($xml instanceof SimpleXMLElement);
php read.php
Ada
bool(true)
The element name becomes a property, and the object it returns is a SimpleXMLElement. Printing it gives its text, which is why no explicit accessor is needed.
XPath one-liners
XPath finds nodes by path, attribute, or text without manual loops. One short query can replace a whole nested loop over children.
Method xpath returns an array of matches. An empty array means nothing matched.
<?php $xml = simplexml_load_string( "<shop><item>Ada</item><item>Bob</item></shop>" ); $items = $xml->xpath("//item"); echo count($items), PHP_EOL; echo $items[1], PHP_EOL;
php xpath.php
2
Bob
Each match is itself a SimpleXMLElement, so index one prints the text of the second item and the same array can be looped when the count is larger.
Build with DOMDocument
DOMDocument builds new XML node by node. You create elements, attach them to parents, and serialize once at the end.
This approach keeps encoding and structure correct. It avoids broken markup from string concatenation.
<?php $dom = new DOMDocument("1.0", "UTF-8"); $dom->formatOutput = true; $root = $dom->createElement("root"); $dom->appendChild($root); $item = $dom->createElement("item", "Ada"); $root->appendChild($item); echo $dom->saveXML();
php build.php
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>Ada</item>
</root>
The declaration comes from the constructor arguments, and formatOutput is what puts each element on its own indented line.
Escape output
Text taken from XML is still untrusted input for HTML output. Escape it at the moment you print it into a page.
Cast the node to string first, then pass it through htmlspecialchars with an explicit charset.
<?php $xml = simplexml_load_string( "<root><item>Tom & Jerry</item></root>" ); echo htmlspecialchars((string) $xml->item, ENT_QUOTES, "UTF-8"), PHP_EOL;
php escape.php
Tom & Jerry
The ampersand that arrived as an entity in the XML leaves again as an HTML entity, so a browser shows the character instead of starting one.
Exercises
- Add a second child to the read example and print both texts in one loop.
- Select the second item with an XPath position, as //item[2].
- Add an attribute to an element in the build example and read it back with getAttribute().
- Feed a broken document to simplexml_load_string, suppress the warnings with libxml_use_internal_errors() and print what the call returned.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
simplexml_load_string()return for a valid document?Answer
A
SimpleXMLElementobjectThe whole document becomes one object, and its child elements are reached as properties.
-
What does
xpath()return when nothing matches?Answer
An empty array
The method always returns an array, and an empty one is how it reports that no node matched.
-
Which DOMDocument call attaches a new element to its parent?
Answer
appendChild()createElement()only builds the node;appendChild()is what puts it into the tree. -
Why does XML text need
htmlspecialchars()before it goes into an HTML page?Answer
It turns markup characters into safe entities
Text that carries a
<or an&would otherwise be read as markup by the browser. -
What does this program print?
<?php $xml = simplexml_load_string("<root><item>Ada</item></root>"); echo $xml->item;Answer
Ada
The property named after the child element prints the text inside it.
-
What does this program print?
<?php $xml = simplexml_load_string("<shop><item>Ada</item><item>Bob</item></shop>"); $items = $xml->xpath("//item"); echo count($items), " ", $items[1];Answer
2 Bob
Both items match, and the index counts from zero, so one is the second item.
-
What does this program print?
<?php $dom = new DOMDocument("1.0", "UTF-8"); $root = $dom->createElement("root"); $dom->appendChild($root); echo $dom->saveXML();Answer
<?xml version="1.0" encoding="UTF-8"?> / <root/>
The declaration comes first and the empty element is written in its short form, all on one line without
formatOutput. -
What does this program print?
<?php $xml = simplexml_load_string("<root><item>Tom & Jerry</item></root>"); echo htmlspecialchars((string) $xml->item, ENT_QUOTES, "UTF-8");Answer
Tom & Jerry
The XML parser already turned the entity into
&, and the escape turns it into&again for HTML. -
A document is glued together from user text with dots instead of DOM calls. What is the typical damage?
Answer
An
&or a<in the text breaks the documentThose two characters start an entity or a tag, so the document stops being well formed.
-
What does
simplexml_load_string()give for a broken document?Answer
false, with a warning about the parse errorThe parse fails, the function returns false and PHP warns; the prose of the read section asks for that check.
The examples call simplexml_load_string(), htmlspecialchars() and count(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.
Article author: Arthur Isaev