W3docs

PHP XML Parsers: A Comprehensive Guide

Learn how to parse XML in PHP with SimpleXML, XMLReader, and DOM. Runnable examples, error handling with libxml, and how to choose the right parser.

XML (eXtensible Markup Language) is a widely used format for exchanging structured data between applications, web services, and platforms. Because so many APIs, configuration files, and feeds still use it, knowing how to read XML in PHP is a practical skill. This guide explains the three built-in XML parsers that ship with PHP — SimpleXML, XMLReader, and DOM — shows runnable examples for each, and helps you pick the right one for your use case.

What is a PHP XML parser?

An XML parser is a library that reads an XML document, checks that it is well-formed, and gives your code structured access to its elements, attributes, and text. PHP ships with three native parsers, all built on the same underlying libxml engine:

  • SimpleXML — a tree-based parser that loads the whole document into an easy-to-use object.
  • DOM — a tree-based parser following the W3C Document Object Model, with a richer API for navigating and editing.
  • XMLReader — a streaming, cursor-based parser that reads one node at a time without loading the full document into memory.

"Tree-based" means the entire document is held in memory as a navigable structure — simple to use but memory-hungry for big files. "Streaming" (also called pull parsing) means the parser walks through the document node by node, which keeps memory usage low for large files.

All examples below use the same sample document, kept inline as a string so you can run them as-is:

$xmlString = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<library>
  <book>
    <title>PHP for Beginners</title>
    <author>Jane Doe</author>
    <year>2021</year>
  </book>
  <book>
    <title>Advanced PHP</title>
    <author>John Smith</author>
    <year>2023</year>
  </book>
</library>
XML;

SimpleXML

SimpleXML provides the quickest way to read XML. You load a document into a SimpleXMLElement object and then reach its data using ordinary object properties — $xml->book[0]->title instead of any method calls. It is ideal for small to medium documents whose structure you already know.

Use simplexml_load_string() for XML you already have as a string, or simplexml_load_file() to read directly from a file or URL.

$xml = simplexml_load_string($xmlString);

// Access a single value by position
echo $xml->book[0]->title . "\n";

// Loop over every <book> element
foreach ($xml->book as $book) {
    echo "{$book->title} by {$book->author} ({$book->year})\n";
}

Output:

PHP for Beginners
PHP for Beginners by Jane Doe (2021)
Advanced PHP by John Smith (2023)

Note that element values are SimpleXMLElement objects, not plain strings. Concatenation or echo casts them to text automatically, but cast with (string) when you need an actual string. See PHP SimpleXML for a deeper look, including reading attributes and namespaces.

XMLReader

XMLReader is a streaming, forward-only parser. Instead of building a tree, it advances through the document one node at a time, so memory stays low no matter how big the file is. That makes it the right choice for large feeds or exports where loading everything at once would exhaust memory.

Call read() to move to the next node, then inspect nodeType and name to decide what to do. Use open() to read from a file or URL, or XML() to read from a string.

$reader = new XMLReader();
$reader->XML($xmlString);

while ($reader->read()) {
    if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'title') {
        echo $reader->readString() . "\n";
    }
}
$reader->close();

Output:

PHP for Beginners
Advanced PHP

The trade-off is convenience: because XMLReader only ever holds one node, there is no random access — you cannot jump back or query arbitrary elements the way you can with a tree. A common pattern is to stream to the element you care about, then hand that subtree to SimpleXML or DOM with expand().

DOM

The DOM extension implements the standard W3C Document Object Model. Like SimpleXML it loads the whole document into a tree, but it exposes a fuller API for navigating nodes, querying with XPath, and creating or modifying elements. Reach for DOM when you need to write or restructure XML, not just read it.

Load XML with loadXML() (from a string) or load() (from a file), then walk the tree with methods such as getElementsByTagName().

$dom = new DOMDocument();
$dom->loadXML($xmlString);

$titles = $dom->getElementsByTagName('title');
foreach ($titles as $title) {
    echo $title->nodeValue . "\n";
}

Output:

PHP for Beginners
Advanced PHP

getElementsByTagName() returns a DOMNodeList you can iterate or index with ->item(0). For more complex queries you can pair DOMDocument with DOMXPath. See PHP XML DOM for the full API.

Handling parse errors

By default, malformed XML triggers PHP warnings that are hard to act on programmatically. Call libxml_use_internal_errors(true) to suppress those warnings and collect structured error objects with libxml_get_errors() instead. All three parsers share this libxml error mechanism.

libxml_use_internal_errors(true);

$badXml = '<library><book><title>Unclosed</book></library>';
$xml = simplexml_load_string($badXml);

if ($xml === false) {
    echo "Failed to parse XML:\n";
    foreach (libxml_get_errors() as $error) {
        echo trim($error->message) . "\n";
    }
    libxml_clear_errors();
}

Output:

Failed to parse XML:
Opening and ending tag mismatch: title line 1 and book
Opening and ending tag mismatch: book line 1 and library
Premature end of data in tag library line 1

Always check the return value of a load function (false on failure) before using the result. For more on these helpers, see PHP libxml.

Choosing the right PHP XML parser

ParserModelMemoryBest for
SimpleXMLTreeHighQuick reads of small/medium documents
DOMTreeHighEditing, XPath queries, building XML
XMLReaderStreamingLowLarge documents read once, top to bottom

In short:

  • Pick SimpleXML when you just want to read known, modestly sized XML with the least code.
  • Pick DOM when you need to modify documents, run XPath queries, or generate XML.
  • Pick XMLReader when the document is large enough that loading it all into memory is a problem.

Conclusion

PHP gives you three native XML parsers, each suited to a different job: SimpleXML for fast, simple reads, DOM for full manipulation, and XMLReader for memory-efficient streaming of large files. Match the parser to your document size and whether you only need to read or also need to write, wrap loads in libxml error handling, and you can parse XML reliably in any PHP project.

To go further, explore PHP SimpleXML parser, PHP XML parser (Expat), and PHP XML DOM.

Practice

Practice
Which of these are built-in PHP XML parsers covered in this guide?
Which of these are built-in PHP XML parsers covered in this guide?
Was this page helpful?