PHP XML Parsers

Su Subhalakshmi Chandran Updated 21 Oct 2026
5 min read ·Lesson 178 of 185
In this post

What Is XML? In simple terms: XML (eXtensible Markup Language) is a text format for structured data, written with tags similar to HTML. Unlike HTML, the tags are not predefined — you invent names that

What Is XML?

In simple terms: XML (eXtensible Markup Language) is a text format for structured data, written with tags similar to HTML. Unlike HTML, the tags are not predefined — you invent names that describe your data: <product>, <price>, <invoice>. Many systems exchange data as XML: RSS and Atom news feeds, sitemaps for search engines, SOAP web services, e-invoicing standards, bank statements, and Microsoft Office files (which are ZIP archives of XML documents).

Technically: An XML document is a tree of elements. Elements can have attributes, text content, and child elements. Documents must be well-formed: exactly one root element, every opening tag closed, tags properly nested, attribute values quoted, and special characters escaped (<, >, &). Namespaces (xmlns) distinguish elements from different vocabularies.

The Example Document Used in This Section

<?xml version="1.0" encoding="UTF-8"?>
<catalog store="GoCourse Shop" updated="2026-10-15">
    <product sku="PEN-01" category="stationery">
        <name>Gel Pen</name>
        <price currency="INR">20.00</price>
        <stock>120</stock>
    </product>
    <product sku="LAMP-01" category="electronics">
        <name>Desk Lamp</name>
        <price currency="INR">1299.00</price>
        <stock>6</stock>
    </product>
    <product sku="MOUSE-01" category="electronics">
        <name>Wireless Mouse</name>
        <price currency="INR">599.00</price>
        <stock>30</stock>
    </product>
</catalog>
PartExample
XML declaration<?xml version="1.0" encoding="UTF-8"?>
Root element<catalog>
Attributesku="PEN-01"
Child element with text<name>Gel Pen</name>

The following lessons assume this document is stored in the variable $catalogXml (or the file catalog.xml).


PHP's XML Tools

PHP offers several XML extensions, which fall into two families:

ToolTypeReads Whole Document Into Memory?Best For
SimpleXMLTree-basedYesQuick, readable access to small and medium documents
DOM (DOMDocument, PHP 8.4 Dom\XMLDocument)Tree-basedYesFull control: editing, XPath, creating documents, HTML
XML Parser (Expat)Event-based (push)NoStreaming large files with callbacks
XMLReaderStream-based (pull)NoStreaming large files with a cursor; combinable with DOM/SimpleXML
XMLWriterWriterNoGenerating large XML documents efficiently

Tree-Based vs Stream-Based

Tree-based (SimpleXML, DOM):           Stream-based (XMLReader, Expat):
read whole file → build tree in memory   read → handle element → forget → next element
→ navigate freely, modify, save          → constant memory, forward-only
  • Tree-based parsers are convenient: you can jump to any element, search with XPath, and modify the document. Memory use grows with the document size — often several times the file size.
  • Stream-based parsers read the document piece by piece. They handle gigabyte-sized files with constant memory but only move forward.

A common rule: use SimpleXML or DOM for documents up to a few megabytes; use XMLReader for large feeds and exports.


A First Taste

<?php
$catalog = simplexml_load_string($catalogXml);

echo "Store: {$catalog['store']}\n";
echo "Products: " . count($catalog->product) . "\n";
echo "First product: {$catalog->product[0]->name}\n";

Output

Store: GoCourse Shop
Products: 3
First product: Gel Pen

SimpleXML maps elements to object properties and attributes to array keys — the details follow in PHP SimpleXML Parser.


Handling Invalid XML

XML from external sources may be malformed. By default, libxml (the library behind SimpleXML and DOM) reports problems as PHP warnings. Collecting them instead allows proper error handling:

<?php
libxml_use_internal_errors(true);

$document = simplexml_load_string('<catalog><product></catalog>');

if ($document === false) {
    $error = libxml_get_errors()[0];
    echo "Invalid XML at line {$error->line}: " . trim($error->message) . "\n";
    libxml_clear_errors();
}

Output

Invalid XML at line 1: Opening and ending tag mismatch: product line 1 and catalog
  1. libxml_use_internal_errors(true) stores errors instead of emitting warnings.
  2. simplexml_load_string() returns false for documents that are not well-formed.
  3. libxml_get_errors() returns LibXMLError objects with the message, line, column, and severity.
  4. libxml_clear_errors() empties the error buffer before the next parse.

Security: XML External Entities (XXE)

XML can define entities, including external entities that load content from files or URLs. A malicious document could use them to read files from your server (file:///etc/passwd) or make the server send requests (XXE attacks).

SituationSafe?
Default settings with libxml 2.9+ (all supported PHP versions)External entities are not loaded
Passing LIBXML_NOENT (substitute entities) or LIBXML_DTDLOAD for untrusted inputDangerous — re-enables entity expansion/loading
libxml_disable_entity_loader()Deprecated since PHP 8.0; no longer needed

Rules for untrusted XML:

  • Do not pass LIBXML_NOENT, LIBXML_DTDLOAD, or LIBXML_DTDATTR when parsing external documents.
  • Limit the size of uploaded or downloaded XML.
  • Treat values extracted from XML like any other input: validate them and escape them on output.

Choosing the Right Parser

TaskRecommended
Read a configuration file or API responseSimpleXML
Find elements with complex conditionsSimpleXML or DOM with XPath
Modify or create documentsDOM (or SimpleXML for simple changes)
Parse HTML pagesDOM — in PHP 8.4, Dom\HTMLDocument
Import a 2 GB product feedXMLReader (expanding each record with SimpleXML/DOM)
Generate a large sitemap or exportXMLWriter
Legacy code with event callbacksXML Parser (Expat)

XML or JSON?

For new APIs between your own systems, JSON is usually simpler (see PHP JSON). XML remains important where standards require it: feeds, sitemaps, SOAP services, government and banking formats, and document formats.


Common Mistakes

Parsing Large Files With Tree-Based Parsers

Effect: Memory exhaustion.

Fix: Use XMLReader for large documents.

Ignoring Parse Errors

Effect: false is used as a document, leading to confusing errors later.

Fix: Check the return value and collect libxml errors.

Enabling Entity Substitution for Untrusted Input

Effect: XXE vulnerabilities.

Fix: Keep default options; never use LIBXML_NOENT with external XML.

Building XML With String Concatenation

Effect: Unescaped & or < in values produce invalid XML.

Fix: Use SimpleXML, DOM, or XMLWriter to generate XML.


Best Practices

  • Choose tree-based parsers for convenience and stream-based parsers for size.
  • Always check whether parsing succeeded and handle errors.
  • Keep libxml's secure defaults for untrusted documents.
  • Use XPath for searching instead of manual nested loops.
  • Generate XML with an XML API, never by concatenating strings.

Official reference: https://www.php.net/manual/en/refs.xml.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro
Ask about this post
AI Ask about this post

Ask questions about PHP XML Parsers and get answers drawn from it.

Signed-in readers only.