Parsing HTML5 with Dom\HTMLDocument

suggest change

PHP 8.4 added a new DOM API in the Dom namespace. Its centerpiece is Dom\HTMLDocument, an HTML5 parser built on the Lexbor library. It parses HTML with the algorithm from the HTML Living Standard, the same one browsers use, so you get the same tree a browser would build. It also brings browser-style methods: querySelector(), querySelectorAll(), closest(), matches(), classList, innerHTML and, in PHP 8.5, outerHTML.

The dom extension is enabled in most PHP builds and needs no other libraries. This article covers parsing, encodings, CSS selectors, reading and changing elements, building documents, serializing, namespaces, Dom\XMLDocument, and how the new API differs from the old DOMDocument. All examples were run with PHP 8.5.

Web scraping shows how to use Dom\HTMLDocument to download pages and crawl a site. This article is about the API itself. For the legacy parser see Parsing HTML from a string and Using XPath, and for building XML the old way see Create XML using DOMDocument.

Creating a document

The constructor is private. You create a document with one of three static methods:

The parser fixes broken markup the way browsers do. It adds the missing <html>, <head> and <body>, closes unclosed <p> elements, untangles misnested tags and adds <tbody> to tables:

<?php
$html = <<<'HTML'
<!DOCTYPE html>
<title>Shop</title>
<p>First paragraph
<p>Second <b>bold <i>both</b> italic</i>
<table><tr><td>cell</table>
HTML;

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

echo $doc->title, "\n";
echo get_class($doc->body), "\n";
echo $doc->saveHtml(), "\n";

Output:

Shop
Dom\HTMLElement
<!DOCTYPE html><html><head><title>Shop</title>
</head><body><p>First paragraph
</p><p>Second <b>bold <i>both</i></b><i> italic</i>
</p><table><tbody><tr><td>cell</td></tr></tbody></table></body></html>

Dom\HTMLDocument has title, head and body properties, just like document in JavaScript. $doc->documentElement is the <html> element.

The parser always builds a complete document, even from a fragment like <b>hi</b>. To get the fragment back, read $doc->body->innerHTML.

Parse errors

HTML has no fatal errors: every input produces a tree. The parser still reports problems it found, as PHP warnings by default. Pass LIBXML_NOERROR to silence them, or collect them with libxml_use_internal_errors():

<?php
$html = '<p class="a" class="b">Fish &amp chips</p><div><span></div><x-widget/>text';

libxml_use_internal_errors(true);
$doc = Dom\HTMLDocument::createFromString($html);
foreach (libxml_get_errors() as $e) {
    printf("line %d col %d: %s\n", $e->line, $e->column, trim($e->message));
}
libxml_clear_errors();

echo $doc->body->innerHTML, "\n";

// LIBXML_NOERROR: no warnings and nothing collected
$doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
var_dump(count(libxml_get_errors()));

Output:

line 1 col 33: tokenizer error missing-semicolon-after-character-reference in Entity, line: 1, column: 33
line 1 col 2: tree error unexpected-token-in-initial-mode in Entity, line: 1, column: 2
line 1 col 56: tree error unexpected-element-in-open-elements-stack in Entity, line: 1, column: 56-58
<p class="a">Fish &amp; chips</p><div><span></span></div><x-widget>text</x-widget>
int(0)

The error names (missing-semicolon-after-character-reference, unexpected-token-in-initial-mode) come from the HTML standard's list of parse errors. "Unexpected token in initial mode" means the document has no <!DOCTYPE html>. Real-world pages almost always have some errors, so LIBXML_NOERROR is the usual choice.

The recovery follows the standard too: the duplicate class attribute is dropped, &amp without a semicolon still decodes, and <x-widget/> is not self-closing (in HTML the / is ignored on non-void elements), so the text ends up inside it.

Encoding

The parser figures out the encoding the way a browser does: a byte order mark comes first, then the $overrideEncoding argument, then <meta charset> (or <meta http-equiv="Content-Type">) in the document, and if there's nothing, UTF-8. The resulting DOM is always UTF-8 inside, whatever the input was:

<?php
// No charset declared: UTF-8 is assumed
$doc = Dom\HTMLDocument::createFromString('<p>Café Müller</p>', LIBXML_NOERROR);
echo $doc->charset, ': ', $doc->body->textContent, "\n";

// Latin-1 bytes with a <meta charset>: decoded to UTF-8 for you
$latin1 = "<meta charset=\"iso-8859-1\"><p>Caf\xE9 M\xFCller</p>";
$doc = Dom\HTMLDocument::createFromString($latin1, LIBXML_NOERROR);
echo $doc->charset, ': ', $doc->body->textContent, "\n";

// Latin-1 bytes without a declaration: tell the parser
$doc = Dom\HTMLDocument::createFromString("<p>Caf\xE9</p>", LIBXML_NOERROR, 'windows-1252');
echo $doc->charset, ': ', $doc->body->textContent, "\n";

// A byte order mark wins over everything
$doc = Dom\HTMLDocument::createFromString("\xEF\xBB\xBF<meta charset=\"iso-8859-1\"><p>Café</p>", LIBXML_NOERROR);
echo $doc->charset, ': ', $doc->body->textContent, "\n";

// saveHtml() writes in the document's encoding
echo bin2hex($doc->saveHtml($doc->querySelector('p'))), "\n";
$doc->charset = 'iso-8859-1';
echo bin2hex($doc->saveHtml($doc->querySelector('p'))), "\n";

Output:

UTF-8: Café Müller
windows-1252: Café Müller
windows-1252: Café
UTF-8: Café
3c703e436166c3a93c2f703e
3c703e436166e93c2f703e

Note that iso-8859-1 is reported as windows-1252. That's not a bug: the WHATWG Encoding Standard says browsers must treat the two labels as the same encoding. textContent, innerHTML and other properties always return UTF-8. Only saveHtml() and saveHtmlFile() convert to the document's encoding, which you can change through the charset property: in the last line é is the single byte e9 instead of the UTF-8 pair c3a9.

When you get HTML over HTTP, the Content-Type header may name the encoding (text/html; charset=Shift_JIS). Pass it as $overrideEncoding, because the parser can't see HTTP headers.

Finding elements with CSS selectors

The examples below use this file, saved as page.html. Notice the unclosed <li> elements:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Gadget store</title>
</head>
<body>
  <nav id="menu">
    <a href="/" class="active">Home</a>
    <a href="/sale">Sale</a>
  </nav>
  <main>
    <article class="product featured" data-sku="A-100">
      <h2>Kettle</h2>
      <p class="price">€29.90</p>
      <ul class="tags"><li>kitchen<li>steel</ul>
      <button disabled>Sold out</button>
    </article>
    <article class="product" data-sku="B-200">
      <h2>Toaster</h2>
      <p class="price">€19.50</p>
      <ul class="tags"><li>kitchen</ul>
      <button>Add to cart</button>
    </article>
    <article class="product" data-sku="C-300">
      <h2>Lamp</h2>
      <p class="price">€12.00 <s>€15.00</s></p>
      <button>Add to cart</button>
    </article>
  </main>
</body>
</html>

querySelector() returns the first matching element or null. querySelectorAll() returns all matches in document order as a Dom\NodeList. Both exist on the document and on every element. Called on an element, they only search inside it:

<?php
$doc = Dom\HTMLDocument::createFromFile(__DIR__ . '/page.html');

echo $doc->title, "\n";
echo $doc->getElementById('menu')->childElementCount, " menu links\n";

// first match or null
$first = $doc->querySelector('article.product h2');
echo 'first: ', $first->textContent, "\n";
var_dump($doc->querySelector('article.missing'));

// all matches, in document order
foreach ($doc->querySelectorAll('article.product') as $article) {
    printf("%-6s %-8s %s\n",
        $article->getAttribute('data-sku'),
        $article->querySelector('h2')->textContent,
        trim($article->querySelector('.price')->firstChild->textContent));
}

// a Dom\NodeList: countable, indexable and iterable
$buttons = $doc->querySelectorAll('button:not([disabled])');
echo count($buttons), ' enabled buttons, the first says "', $buttons[0]->textContent, "\"\n";

Output:

Gadget store
2 menu links
first: Kettle
NULL
A-100  Kettle   €29.90
B-200  Toaster  €19.50
C-300  Lamp     €12.00
2 enabled buttons, the first says "Add to cart"

$article->querySelector('.price')->firstChild is the text node before <s>, so for the lamp we get only the current price.

The selector engine supports modern CSS selectors, including :has(), :is(), :not() with complex arguments, the :nth-* family and attribute operators:

<?php
$doc = Dom\HTMLDocument::createFromFile(__DIR__ . '/page.html');

$selectors = [
    'article:has(s) h2',                 // product with a struck-out old price
    'article:nth-child(2) h2',
    'article:not(:has(ul)) h2',
    '[data-sku^="B"] h2',
    'h2 + .price',
    'nav a:first-child',
    'a[href="/sale"]',
    'p.price:has(> s)',
    'li:last-child',
];
foreach ($selectors as $sel) {
    $texts = [];
    foreach ($doc->querySelectorAll($sel) as $el) {
        $texts[] = trim($el->textContent);
    }
    printf("%-34s %s\n", $sel, implode(' | ', $texts));
}
try {
    $doc->querySelector('article >> h2');
} catch (DOMException $e) {
    echo get_class($e), ': ', $e->getMessage(), ' code=', $e->getCode(), "\n";
}

Output:

article:has(s) h2                  Lamp
article:nth-child(2) h2            Toaster
article:not(:has(ul)) h2           Lamp
[data-sku^="B"] h2                 Toaster
h2 + .price                        €29.90 | €19.50 | €12.00 €15.00
nav a:first-child                  Home
a[href="/sale"]                    Sale
p.price:has(> s)                   €12.00 €15.00
li:last-child                      steel | kitchen
DOMException: Invalid selector (Selectors. Unexpected token: >) code=12

li:last-child found two elements because the parser closed the first <li> when it saw the second one. An invalid selector throws DOMException with code Dom\SYNTAX_ERR (12). Selectors that need a browser, such as :hover or :visited, never match.

Besides selectors you can use the classic methods: getElementById(), getElementsByTagName() and getElementsByClassName(). Note that these return live collections, see the section on removing nodes below.

closest() and matches()

matches($selector) tells you if an element matches a selector. closest($selector) walks up from the element itself through its ancestors and returns the first one that matches, or null. They're handy when you find an element and need its context:

<?php
$doc = Dom\HTMLDocument::createFromFile(__DIR__ . '/page.html');

foreach ($doc->querySelectorAll('button') as $button) {
    // walk up to the nearest ancestor (or self) matching a selector
    $product = $button->closest('article.product');
    printf("%-12s in %s, featured: %s, sold out: %s\n",
        $button->textContent,
        $product->querySelector('h2')->textContent,
        $product->matches('.featured') ? 'yes' : 'no',
        $button->matches('[disabled]') ? 'yes' : 'no');
}

// closest() returns null when no ancestor matches
var_dump($doc->querySelector('h2')->closest('nav'));

Output:

Sold out     in Kettle, featured: yes, sold out: yes
Add to cart  in Toaster, featured: no, sold out: no
Add to cart  in Lamp, featured: no, sold out: no
NULL

Attributes and classList

classList is a Dom\TokenList, a live view of the class attribute with add(), remove(), toggle(), replace() and contains(). The className and id properties read and write the class and id attributes as strings:

<?php
$doc = Dom\HTMLDocument::createFromFile(__DIR__ . '/page.html');
$article = $doc->querySelector('article');

echo $article->className, "\n";
$classes = $article->classList;         // Dom\TokenList, live
echo count($classes), ' classes: ', implode(', ', iterator_to_array($classes)), "\n";
var_dump($classes->contains('featured'));

$classes->add('on-sale', 'new');
$classes->remove('featured');
$classes->toggle('new');                 // removes it, returns false
$classes->toggle('compact', true);       // force on
$classes->replace('product', 'item');
echo $article->getAttribute('class'), "\n";

// Attributes
echo $article->getAttribute('data-sku'), "\n";
var_dump($article->getAttribute('data-missing'));   // null, not ""
var_dump($article->hasAttribute('data-sku'));
$article->setAttribute('data-stock', '0');
$article->removeAttribute('data-sku');
print_r($article->getAttributeNames());

$button = $article->querySelector('button');
$button->toggleAttribute('disabled');    // boolean attribute off
echo $button->outerHTML, "\n";
$button->id = 'buy-kettle';
echo $button->outerHTML, "\n";

Output:

product featured
2 classes: product, featured
bool(true)
item on-sale compact
A-100
NULL
bool(true)
Array
(
    [0] => class
    [1] => data-stock
)
<button>Sold out</button>
<button id="buy-kettle">Sold out</button>

There's no dataset property, so read data-* attributes with getAttribute(). Unlike DOMElement::getAttribute(), which returns "" for a missing attribute, the new getAttribute() returns null, so you can tell "missing" from "empty".

textContent, innerHTML and outerHTML

<?php
$doc = Dom\HTMLDocument::createFromString(
    '<div id="note"><p>Fish &amp; <b>chips</b></p>
<p>&lt;script&gt; is escaped</p></div>', LIBXML_NOERROR);
$note = $doc->getElementById('note');

echo "textContent: ", $note->textContent, "\n";
echo "innerHTML:   ", $note->innerHTML, "\n";
echo "outerHTML:   ", $note->querySelector('b')->outerHTML, "\n";

// Setting textContent: the string is text, never markup
$note->querySelector('b')->textContent = '<i>peas</i>';
echo $note->firstElementChild->innerHTML, "\n";

// Setting innerHTML: the string is parsed as an HTML fragment
$note->innerHTML = '<ul><li>one<li>two</ul>';
echo $note->outerHTML, "\n";
echo $note->querySelectorAll('li')->length, " items\n";

// insertAdjacentHTML() parses a fragment next to the element
$note->querySelector('ul')->insertAdjacentHTML(Dom\AdjacentPosition::BeforeBegin, '<h3>List</h3>');
$note->querySelector('ul')->insertAdjacentHTML(Dom\AdjacentPosition::BeforeEnd, '<li>three');
echo $note->innerHTML, "\n";

Output:

textContent: Fish & chips
<script> is escaped
innerHTML:   <p>Fish &amp; <b>chips</b></p>
<p>&lt;script&gt; is escaped</p>
outerHTML:   <b>chips</b>
Fish &amp; <b>&lt;i&gt;peas&lt;/i&gt;</b>
<div id="note"><ul><li>one</li><li>two</li></ul></div>
2 items
<h3>List</h3><ul><li>one</li><li>two</li><li>three</li></ul>

insertAdjacentHTML() takes a Dom\AdjacentPosition enum (BeforeBegin, AfterBegin, BeforeEnd, AfterEnd), not a string like in JavaScript. There are also insertAdjacentElement() and insertAdjacentText().

Use textContent (or text nodes) for untrusted data. Assigning user input to innerHTML is the same XSS hole as in a browser.

Building a document

createEmpty() gives you a document with no nodes, not even <html>. To start from a proper skeleton, use createHTMLDocument() from the document's implementation. It creates the doctype, <html>, <head>, <title> and <body>:

<?php
$products = [
    ['Kettle', 29.9, ['kitchen', 'steel']],
    ['Tom & Jerry <DVD>', 9.5, []],
];

// doctype, <html>, <head>, <title> and <body> in one call
$doc = Dom\HTMLDocument::createEmpty()->implementation->createHTMLDocument('Price list');
$doc->documentElement->setAttribute('lang', 'en');

$meta = $doc->createElement('meta');
$meta->setAttribute('charset', 'utf-8');
$doc->head->prepend($meta);

$table = $doc->createElement('table');
foreach ($products as [$name, $price, $tags]) {
    $nameCell = $doc->createElement('td');
    $nameCell->textContent = $name;                 // escaped on output
    $priceCell = $doc->createElement('td');
    $priceCell->append(number_format($price, 2));   // a string becomes a text node
    $priceCell->className = 'num';

    $tr = $doc->createElement('tr');
    $tr->append($nameCell, $priceCell);
    if ($tags) {
        $tr->setAttribute('data-tags', implode(' ', $tags));
    }
    $table->append($tr);
}
$doc->body->append($table);

echo $doc->saveHtml(), "\n";
echo $doc->title, "\n";

Output:

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Price list</title></head><body><table><tr data-tags="kitchen steel"><td>Kettle</td><td class="num">29.90</td></tr><tr><td>Tom &amp; Jerry &lt;DVD&gt;</td><td class="num">9.50</td></tr></table></body></html>
Price list

Things to note:

If your page is mostly fixed markup with a few dynamic parts, it's simpler to parse a template string with createFromString() and fill in the parts with querySelector() and textContent.

Modifying and removing nodes

Here's a (deliberately simple) cleanup of user-submitted HTML. It removes elements, drops attributes, unwraps links and renames an element:

<?php
$comment = <<<'HTML'
<p onclick="steal()">Nice post! <script>alert(1)</script>
<a href="https://example.com/x" target="_blank">my site</a>
<a href="javascript:alert(2)">click</a>
<center>old school</center>
<img src="a.png" onerror="steal()">
HTML;

$doc = Dom\HTMLDocument::createFromString($comment, LIBXML_NOERROR);
$body = $doc->body;

// querySelectorAll() returns a static list: removing while iterating is safe
foreach ($body->querySelectorAll('script, img') as $el) {
    $el->remove();
}

// drop every on* attribute
foreach ($body->querySelectorAll('*') as $el) {
    foreach ($el->getAttributeNames() as $name) {
        if (str_starts_with($name, 'on')) {
            $el->removeAttribute($name);
        }
    }
}

foreach ($body->querySelectorAll('a') as $a) {
    if (!str_starts_with($a->getAttribute('href') ?? '', 'https://')) {
        $a->replaceWith($a->textContent);          // keep the text, drop the link
        continue;
    }
    $a->setAttribute('rel', 'nofollow noopener');
    $a->after(' (external)');
}

// replace an obsolete element with a new one, moving its children
foreach ($body->querySelectorAll('center') as $center) {
    $div = $doc->createElement('div');
    $div->className = 'centered';
    $div->append(...$center->childNodes);
    $center->replaceWith($div);
}

echo $body->innerHTML, "\n";

Output:

<p>Nice post! 
<a href="https://example.com/x" target="_blank" rel="nofollow noopener">my site</a> (external)
click
</p><div class="centered">old school</div>

The <center> block closed the open <p>, as it would in a browser. Appending a node that is already in the tree moves it, which is how $div->append(...$center->childNodes) moves the children. For a real HTML sanitizer, use a dedicated allow-list library such as symfony/html-sanitizer. A deny-list like the one above is easy to get wrong.

Live collections

querySelectorAll() returns a snapshot. getElementsByTagName(), getElementsByClassName(), children and childNodes are live: they update as the tree changes. Removing elements while you iterate a live collection skips elements:

<?php
$doc = Dom\HTMLDocument::createFromString('<i>1</i><i>2</i><i>3</i><i>4</i>', LIBXML_NOERROR);

$live = $doc->getElementsByTagName('i');      // Dom\HTMLCollection, live
foreach ($live as $i) {
    $i->remove();
}
echo $doc->body->innerHTML, "\n";             // half of them survived

foreach (iterator_to_array($live) as $i) {    // copy first
    $i->remove();
}
echo '[', $doc->body->innerHTML, "]\n";

Output:

<i>2</i><i>4</i>
[]

Saving the document

saveHtml() serializes the whole document, or a single node if you pass one. saveHtmlFile() writes to a file and returns the number of bytes. saveXml() produces XHTML (XML syntax) instead. To copy nodes from one document into another, use importNode():

<?php
$doc = Dom\HTMLDocument::createFromString(
    '<!DOCTYPE html><title>T</title><p class=x>a<br>b &copy; <input disabled>', LIBXML_NOERROR);
$p = $doc->querySelector('p');

echo $doc->saveHtml(), "\n";        // whole document
echo $doc->saveHtml($p), "\n";      // one node, same as $p->outerHTML
echo $doc->saveXml($p), "\n";       // XML syntax: self-closed, namespaced

$bytes = $doc->saveHtmlFile(__DIR__ . '/out.html');
echo $bytes, " bytes written\n";

// copy a node into another document
$other = Dom\HTMLDocument::createFromString('<div id="box"></div>', LIBXML_NOERROR);
$other->getElementById('box')->append($other->importNode($p, true));
echo $other->body->innerHTML, "\n";

Output:

<!DOCTYPE html><html><head><title>T</title></head><body><p class="x">a<br>b © <input disabled=""></p></body></html>
<p class="x">a<br>b © <input disabled=""></p>
<p xmlns="http://www.w3.org/1999/xhtml" class="x">a<br />b © <input disabled="" /></p>
116 bytes written
<div id="box"><p class="x">a<br>b © <input disabled=""></p></div>

The serializer follows the HTML standard: attribute values are always quoted, void elements like <br> have no closing tag, and entities such as &copy; are written as the actual character. Only &, <, > (and " in attributes) and non-breaking spaces are escaped.

Namespaces and XPath

In the new API, HTML elements live in the XHTML namespace (http://www.w3.org/1999/xhtml), as the DOM standard requires. SVG and MathML embedded in HTML get their own namespaces. tagName is upper-case for HTML elements, localName is always the name as written:

<?php
$html = '<p>Logo: <svg viewBox="0 0 10 10"><circle r="5"/></svg></p>';
$doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);

foreach (['p', 'svg', 'circle'] as $name) {
    $el = $doc->getElementsByTagName($name)[0];
    printf("%-7s tagName=%-7s localName=%-7s ns=%s\n",
        $name, $el->tagName, $el->localName, $el->namespaceURI);
}

// XPath sees the namespace: a bare name matches nothing
$xpath = new Dom\XPath($doc);
echo count($xpath->query('//p')), "\n";
$xpath->registerNamespace('h', 'http://www.w3.org/1999/xhtml');
echo count($xpath->query('//h:p')), "\n";

// ... unless you opt out of the HTML namespace when parsing
$doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS);
$xpath = new Dom\XPath($doc);
echo count($xpath->query('//p')), "\n";
var_dump($doc->querySelector('p')->namespaceURI);

Output:

p       tagName=P       localName=p       ns=http://www.w3.org/1999/xhtml
svg     tagName=svg     localName=svg     ns=http://www.w3.org/2000/svg
circle  tagName=circle  localName=circle  ns=http://www.w3.org/2000/svg
0
1
1
NULL

This trips up people moving XPath code from DOMDocument, where //p works. Either register a prefix for the XHTML namespace or parse with Dom\HTML_NO_DEFAULT_NS. The new Dom\XPath class replaces DOMXPath for Dom\ documents. CSS selectors are not affected by the namespace, so in most cases querySelectorAll() is the easier choice. XPath itself is covered in Using XPath.

Dom\XMLDocument

The same API is available for XML through Dom\XMLDocument, with createFromString(), createFromFile() and createEmpty(). It uses libxml2's XML parser, but you get the modern node classes, querySelector(), standards-compliant namespace handling and formatOutput:

<?php
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
  <title>Release notes</title>
  <entry><title>PHP 8.4</title><media:thumbnail url="84.png"/></entry>
  <entry><title>PHP 8.5</title><media:thumbnail url="85.png"/></entry>
</feed>
XML;

$doc = Dom\XMLDocument::createFromString($xml);
echo $doc->xmlVersion, ' ', $doc->xmlEncoding, "\n";

// CSS selectors work on XML too; element names are case-sensitive
foreach ($doc->querySelectorAll('entry > title') as $title) {
    echo $title->textContent, "\n";
}

// namespaced elements: use the local name with a | prefix wildcard
foreach ($doc->querySelectorAll('*|thumbnail') as $thumb) {
    echo $thumb->tagName, ' ', $thumb->namespaceURI, ' ', $thumb->getAttribute('url'), "\n";
}

// build and pretty-print
$entry = $doc->createElementNS('http://www.w3.org/2005/Atom', 'entry');
$entry->append($doc->createElementNS('http://www.w3.org/2005/Atom', 'title'));
$entry->firstElementChild->textContent = 'PHP 8.6 & beyond';
$doc->documentElement->append($entry);
$doc->formatOutput = true;
echo $doc->saveXml($entry), "\n";

// unlike HTML, malformed XML is an error: the parse throws
libxml_use_internal_errors(true);
try {
    Dom\XMLDocument::createFromString('<a><b></a>');
} catch (DOMException $e) {
    echo $e->getMessage(), "\n";
    echo '  ', trim(libxml_get_errors()[0]->message), "\n";
}

Output:

1.0 UTF-8
PHP 8.4
PHP 8.5
media:thumbnail http://search.yahoo.com/mrss/ 84.png
media:thumbnail http://search.yahoo.com/mrss/ 85.png
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>PHP 8.6 &amp; beyond</title>
</entry>
XML fragment is not well-formed
  Opening and ending tag mismatch: b line 1 and a

createElementNS() puts the new elements in the Atom namespace, and the serializer adds the xmlns declaration where needed. With the old DOMDocument you would have to manage namespace declarations yourself.

A file that can't be opened makes createFromFile() (for both classes) emit a warning and throw a plain Exception:

<?php
try {
    $doc = @Dom\HTMLDocument::createFromFile('missing.html');
} catch (Exception $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

Output:

Exception: Cannot open file 'missing.html'

Differences from DOMDocument

The old DOMDocument::loadHTML() uses libxml2's HTML 4 parser, which predates HTML5. The same input can give a different tree:

<?php
$html = '<p>Zürich<div>block</div><template><li>x</template><script>if (a</b) {}</script>';

libxml_use_internal_errors(true);
$old = new DOMDocument();
$old->loadHTML($html);
$errors = count(libxml_get_errors());
libxml_clear_errors();

$new = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);

echo "DOMDocument ($errors errors):\n", $old->saveHTML($old->getElementsByTagName('body')[0]), "\n";
echo "Dom\\HTMLDocument:\n", $new->saveHtml($new->body), "\n\n";

$p1 = $old->getElementsByTagName('p')[0];
$p2 = $new->querySelector('p');
var_dump($p1->tagName, $p2->tagName);
var_dump($p1->getAttribute('id'), $p2->getAttribute('id'));
var_dump($p1->namespaceURI, $p2->namespaceURI);

Output:

DOMDocument (3 errors):
<body><p>Zürich</p><div>block</div><template><li>x</li></template><script>if (a</script></body>
Dom\HTMLDocument:
<body><p>Zürich</p><div>block</div><template><li>x</li></template><script>if (a</b) {}</script></body>

string(1) "p"
string(1) "P"
string(0) ""
NULL
NULL
string(28) "http://www.w3.org/1999/xhtml"

The old parser mangled the UTF-8 text (it assumes ISO-8859-1 without a <meta charset>), complained about the <template> tag it doesn't know, and cut the script at </b, which an HTML5 parser correctly treats as part of the script.

DOMDocument Dom\HTMLDocument
Parser libxml2, HTML 4 Lexbor, HTML5 standard
Default encoding ISO-8859-1 unless declared UTF-8 unless declared
Parse errors Warnings for HTML5 tags and minor issues Spec-defined errors, silence with LIBXML_NOERROR
Element namespace none XHTML (Dom\HTML_NO_DEFAULT_NS to opt out)
tagName / nodeName p P
Missing attribute getAttribute() returns "" returns null
CSS selectors no querySelector(), querySelectorAll(), closest(), matches()
innerHTML, classList no yes (outerHTML in 8.5)
Creating new DOMDocument() + loadHTML() static createFromString() / createFromFile() / createEmpty()
XPath DOMXPath Dom\XPath

The two APIs use separate class hierarchies (DOMElement vs Dom\Element), so you can't append a node from one to a document of the other. To bring legacy nodes over, use $doc->importLegacyNode($domNode, true). For SimpleXML there's Dom\import_simplexml(). The old classes aren't deprecated, so existing code keeps working, but for new code that handles HTML, use Dom\HTMLDocument.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents