PHP DOM Parser

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

What Is the DOM? In simple terms: The DOM (Document Object Model) represents an XML or HTML document as a tree of nodes — elements, attributes, text — that you can read, search, and change freely: ins

What Is the DOM?

In simple terms: The DOM (Document Object Model) represents an XML or HTML document as a tree of nodes — elements, attributes, text — that you can read, search, and change freely: insert new elements anywhere, move them, delete them, and save the result. It is the same model JavaScript uses for web pages, so the method names will feel familiar.

Technically: PHP's DOM extension implements the W3C DOM standard with classes such as DOMDocument, DOMElement, DOMNode, DOMNodeList, and DOMXPath. Documents are parsed with libxml into a tree held in memory. PHP 8.4 added a modern, standards-compliant API under the Dom0 namespace — including Dom\HTMLDocument`, an HTML5 parser with CSS selector support.

DOM vs SimpleXML

SimpleXMLDOM
Reading dataVery conciseMore verbose
Modifying structure (insert, move, remove)LimitedFull control
Pretty-printed outputNoformatOutput
XPathxpath()DOMXPath (with evaluate() for numbers and strings)
HTML documentsNoYes (loadHTML(), PHP 8.4 Dom\HTMLDocument)

Both work on the same underlying libxml tree, and simplexml_import_dom() / dom_import_simplexml() convert between them.

The examples use the catalog document from PHP XML Parsers ($catalogXml).


Loading and Reading a Document

<?php
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML($catalogXml);

echo "Root: " . $doc->documentElement->tagName . "\n";
echo "Store: " . $doc->documentElement->getAttribute('store') . "\n";

foreach ($doc->getElementsByTagName('product') as $product) {
    $name = $product->getElementsByTagName('name')->item(0)->textContent;
    printf("%-9s %s\n", $product->getAttribute('sku'), $name);
}

Output

Root: catalog
Store: GoCourse Shop
PEN-01    Gel Pen
LAMP-01   Desk Lamp
MOUSE-01  Wireless Mouse

How It Works

  1. loadXML() parses a string (load() parses a file) and returns false for invalid XML.
  2. preserveWhiteSpace = false discards the whitespace-only text nodes between elements (the indentation), which simplifies navigation and enables clean re-formatting later.
  3. documentElement is the root element (<catalog>).
  4. getElementsByTagName() returns a live DOMNodeList of all matching descendants; item(0) gets the first.
  5. getAttribute() reads an attribute; textContent returns all text inside a node.

Unlike SimpleXML, these values are plain PHP strings — no casting is needed.

Key Node Properties and Methods

MemberPurpose
$node->nodeName, $element->tagNameName of the node / element
$node->textContentAll text inside the node (read and write)
$element->getAttribute('x'), hasAttribute(), setAttribute()Attribute access
$node->parentNode, childNodes, firstChild, nextSiblingTree navigation (includes text nodes)
$element->firstElementChild, nextElementSibling, childElementCountNavigation that skips text nodes (PHP 8.0+)

XPath With DOMXPath

<?php
$doc = new DOMDocument();
$doc->loadXML($catalogXml);
$xpath = new DOMXPath($doc);

foreach ($xpath->query('//product[@category="electronics"]/name') as $node) {
    echo $node->textContent . "\n";
}

var_dump($xpath->evaluate('sum(//product/stock)'));
var_dump($xpath->evaluate('count(//product[stock < 10])'));
echo $xpath->evaluate('string(//product[@sku="LAMP-01"]/price/@currency)') . "\n";

Output

Desk Lamp
Wireless Mouse
float(156)
float(1)
INR
  • query() returns a DOMNodeList of matching nodes.
  • evaluate() also returns computed values: XPath functions like sum(), count(), and string() produce numbers (as floats) and strings directly — no PHP loop required.
  • Namespaced documents require $xpath->registerNamespace('prefix', 'uri') before querying, just as with SimpleXML.

Modifying a Document

<?php
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$doc->loadXML($catalogXml);
$xpath = new DOMXPath($doc);

// 1. Change a value
$lampStock = $xpath->query('//product[@sku="LAMP-01"]/stock')->item(0);
$lampStock->textContent = '5';

// 2. Remove an element
$xpath->query('//product[@sku="MOUSE-01"]')->item(0)->remove();

// 3. Create and append a new element
$bag = $doc->createElement('product');
$bag->setAttribute('sku', 'BAG-02');
$bag->setAttribute('category', 'bags');

$name = $doc->createElement('name');
$name->textContent = 'Backpack';
$bag->appendChild($name);

$price = $doc->createElement('price');
$price->setAttribute('currency', 'INR');
$price->textContent = '899.00';
$bag->appendChild($price);

$stock = $doc->createElement('stock');
$stock->textContent = '0';
$bag->appendChild($stock);

$doc->documentElement->appendChild($bag);

echo $doc->saveXML();

Output

<?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>5</stock>
  </product>
  <product sku="BAG-02" category="bags">
    <name>Backpack</name>
    <price currency="INR">899.00</price>
    <stock>0</stock>
  </product>
</catalog>

Step-by-Step Explanation

  1. Assigning textContent replaces an element's text; special characters are escaped automatically.
  2. remove() (PHP 8.0+) deletes a node from the tree; the older equivalent is $node->parentNode->removeChild($node).
  3. New nodes are created by the document (createElement()) and then attached with appendChild(). Other methods include insertBefore(), replaceChild(), and PHP 8's before(), after(), prepend(), and append().
  4. formatOutput = true (combined with preserveWhiteSpace = false when loading) produces neatly indented output; saveXML() returns the document as a string, and save($file) writes it to a file.

Note: Like SimpleXML's addChild(), the second argument of createElement('name', $value) does not escape & correctly. Set textContent instead, as shown.


Parsing HTML

PHP 8.4+: Dom\HTMLDocument

PHP 8.4's HTML5 parser handles real-world HTML exactly as browsers do and supports CSS selectors:

<?php
$html = <<<HTML
<!DOCTYPE html>
<html>
<body>
  <ul id="courses">
    <li class="course">PHP</li>
    <li class="course new">Laravel</li>
    <li>About us</li>
  </ul>
  <a href="/courses/php">Start learning</a>
</body>
</html>
HTML;

$doc = Dom\HTMLDocument::createFromString($html);

foreach ($doc->querySelectorAll('li.course') as $item) {
    echo "Course: {$item->textContent}\n";
}

echo "New: " . $doc->querySelector('li.new')->textContent . "\n";
echo "Link: " . $doc->querySelector('a')->getAttribute('href') . "\n";

Output

Course: PHP
Course: Laravel
New: Laravel
Link: /courses/php

querySelector() and querySelectorAll() accept the same CSS selectors as JavaScript. The new Dom0 classes are also available for XML (Dom\XMLDocument`) with improved, standards-compliant behavior.

Older Versions: DOMDocument::loadHTML()

Before PHP 8.4, loadHTML() used libxml's HTML 4 parser. It emits warnings for HTML5 elements (suppress them with libxml_use_internal_errors(true)), may misinterpret UTF-8 text unless the document declares its encoding, and requires XPath instead of CSS selectors. Prefer Dom\HTMLDocument on PHP 8.4+.

When processing HTML from other websites (web scraping), respect their terms of use and robots.txt, and treat all extracted content as untrusted.


Common Mistakes

Forgetting preserveWhiteSpace = false

Effect: firstChild returns whitespace text nodes; formatOutput cannot re-indent.

Fix: Disable whitespace preservation before loading, or use element-only navigation (firstElementChild).

Creating Nodes Without the Document

Effect: "Wrong Document Error" when appending nodes from another document.

Fix: Create nodes with the target document, or use importNode().

Modifying a Live DOMNodeList While Iterating

Effect: Skipped elements when removing nodes inside a foreach over getElementsByTagName().

Fix: Copy the nodes first (iterator_to_array($list)) or iterate backwards.

Using createElement() With Unescaped Text

Effect: Warnings and truncated values for text containing &.

Fix: Set textContent.


Best Practices

  • Use DOM when you need to modify document structure, pretty-print output, or parse HTML.
  • Load with preserveWhiteSpace = false and save with formatOutput = true for readable output.
  • Use DOMXPath::evaluate() for searches and calculations.
  • Set text through textContent to ensure correct escaping.
  • On PHP 8.4+, use Dom\HTMLDocument with CSS selectors for HTML.

Official reference: https://www.php.net/manual/en/book.dom.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 DOM Parser and get answers drawn from it.

Signed-in readers only.