PHP DOM Parser

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 217 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes 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 AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.