For HTML on PHP 8.4 or later, use Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR), then querySelector() and querySelectorAll() with CSS selectors. On PHP 8.3 and older, use DOMDocument::loadHTML() with libxml_use_internal_errors(true) and query it with DOMXPath. For XML, simplexml_load_string() is the shortest path, and XMLReader streams files too big to load. Don't parse HTML with regular expressions.
PHP ships several parsers, in extensions a standard build enables: dom (DOMDocument and, since PHP 8.4, the Dom\HTMLDocument and Dom\XMLDocument classes), SimpleXML, and XMLReader. They all build a tree you can search and change, except XMLReader, which reads one node at a time. The sections below cover the modern HTML5 parser, the classic DOMDocument route with its encoding trap, SimpleXML, namespaced feeds, editing and saving a document, and streaming a large file, then a table to pick from.
Regular expressions are the wrong tool for HTML. Attributes come in any order, with double, single or no quotes; a value can contain >; tags nest; comments, scripts and CDATA hide markup that isn't markup; and real pages leave tags unclosed. A pattern that handles today's page breaks on the next one. A parser deals with all of it the way a browser does. Every example parses a string, so nothing here needs the network. Each example runs on this page: hit Run, then edit the code and run it again.
1Dom\HTMLDocument and CSS selectors (PHP 8.4+)Recommended
PHP 8.4 added Dom\HTMLDocument, built on the lexbor HTML5 parser. It reads a page the way a browser does, understands every HTML5 tag, treats input as UTF-8 by default, and adds the browser API you already know: querySelector(), querySelectorAll(), classList, innerHTML and closest(). Create it with the static createFromString() (or createFromFile()), not with new. Pass LIBXML_NOERROR for HTML you didn't write: without it, each spot that breaks the HTML5 rules prints a warning.
<?php // Real-world HTML: no doctype, unclosed <li>, a bare & in text $html = <<<'HTML' <title>Shop & more</title> <nav> <a href="/">Home</a> <a href="/sale" class="active">Sale</a> </nav> <ul id="products"> <li class="item" data-price="9.50">Coffee mug <li class="item sale" data-price="4.00">Sticker <b>pack</b> <li class="item" data-price="12">Tote bag </ul> HTML; // LIBXML_NOERROR: don't print a warning for each parse error $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR); echo $doc->title, "\n"; // One element: querySelector returns the first match or null $active = $doc->querySelector('nav a.active'); echo $active->textContent, ' -> ', $active->getAttribute('href'), "\n"; // All matches: any CSS selector works foreach ($doc->querySelectorAll('#products > li.item') as $li) { $name = trim($li->textContent); $price = (float) $li->getAttribute('data-price'); printf("%-12s %6.2f\n", $name, $price); } echo count($doc->querySelectorAll('li.sale')), " on sale\n"; var_dump($doc->querySelector('table')); // no match var_dump($active->getAttribute('title')); // no such attribute // The parser fixed the markup the way a browser does echo $doc->querySelector('#products')->innerHTML, "\n";
Output
$doc->title gives Shop & more, and the selector nav a.active finds Sale -> /sale. Text and attributes come back as strings, so cast data-price before doing math. A selector with no match returns NULL, and so does getAttribute() for an attribute that isn't there. The last lines show the repair: each unclosed <li> now ends with </li>, as in a browser. Without LIBXML_NOERROR this input prints Warning: Dom\HTMLDocument::createFromString(): tree error unexpected-token-in-initial-mode because it has no <!DOCTYPE html>. An invalid selector throws a DOMException.
2DOMDocument and DOMXPath (PHP 8.3 and older)
Before 8.4, the answer is DOMDocument::loadHTML(). It uses libxml2's HTML 4 parser, which has two traps. It warns about every HTML5 tag it doesn't know, such as <nav> and <section>, so call libxml_use_internal_errors(true) first and read the messages with libxml_get_errors() if you want them (rather than hiding everything with @). And with no charset in the markup it assumes ISO-8859-1, so UTF-8 text turns into mojibake. It has no CSS selectors; use XPath through DOMXPath, or getElementsByTagName() and getElementById() for simple lookups.
<?php $html = <<<'HTML' <nav><a href="/sale" class="link active">Sale</a></nav> <section> <h2>Café menu</h2> <ul> <li data-price="3.20">Espresso</li> <li data-price="4.10">Flat white</li> </ul> </section> HTML; // Collect libxml's complaints instead of printing them as warnings libxml_use_internal_errors(true); // Trap: without a charset, loadHTML reads the bytes as ISO-8859-1 $doc = new DOMDocument(); $doc->loadHTML($html); $h2 = $doc->getElementsByTagName('h2')->item(0); echo 'No charset: ', $h2->textContent, "\n"; libxml_clear_errors(); // Fix: declare UTF-8 in front of the markup $doc = new DOMDocument(); $doc->loadHTML('<meta charset="utf-8">' . $html); $h2 = $doc->getElementsByTagName('h2')->item(0); echo 'Charset: ', $h2->textContent, "\n"; // HTML5 tags are "invalid" to this HTML 4 parser, but still parsed foreach (libxml_get_errors() as $error) { echo 'libxml: ', trim($error->message), "\n"; } libxml_clear_errors(); // XPath does the querying $xpath = new DOMXPath($doc); foreach ($xpath->query('//section//li') as $li) { echo $li->textContent, ': ', $li->getAttribute('data-price'), "\n"; } // class="link active" needs contains(), padded with spaces $active = '//a[contains(concat(" ", @class, " "), " active ")]'; echo $xpath->query($active)->item(0)->getAttribute('href'), "\n"; // evaluate() returns numbers and strings directly echo $xpath->evaluate('count(//li)'), " items\n"; echo $xpath->evaluate('string(//li[2])'), "\n"; // A missing attribute is an empty string here, not null var_dump($h2->getAttribute('id'));
Output
The first line, No charset: Café menu, is the encoding bug: the two UTF-8 bytes of é were read as two Latin-1 characters. Putting <meta charset="utf-8"> in front fixes it (Café menu); the older trick of prepending <?xml encoding="UTF-8"> also works, but it shows up again in saveHTML() output. The collected errors are only Tag nav invalid and Tag section invalid, and the tags are parsed anyway. XPath has no class selector, so matching one class out of "link active" takes the concat() pattern. Unlike Dom\HTMLDocument, a missing attribute here is string(0) "", not NULL.
3SimpleXML for XML
For XML you control, such as a config file, an API response or an export, simplexml_load_string() (or simplexml_load_file()) is the least code. Child elements read like properties, repeated elements iterate with foreach, attributes read like array keys, and xpath() returns an array of matches. Every value is a SimpleXMLElement, not a string, so cast it with (string), (int) or (float) before comparing, doing math, using it as an array key or passing it to json_encode().
<?php $xml = <<<'XML' <?xml version="1.0" encoding="UTF-8"?> <library> <book id="b1" lang="en"> <title>Dune</title> <author>Frank Herbert</author> <year>1965</year> <price currency="USD">9.99</price> </book> <book id="b2" lang="fr"> <title>L'Étranger</title> <author>Albert Camus</author> <year>1942</year> <price currency="EUR">7.50</price> </book> </library> XML; $library = simplexml_load_string($xml); // Child elements are properties, attributes are array keys $first = $library->book[0]; echo $first->title, ' by ', $first->author, "\n"; echo 'id=', $first['id'], ', currency=', $first->price['currency'], "\n"; // Each value is a SimpleXMLElement: cast before comparing or doing math var_dump($first->year); $decade = intdiv((int) $first->year, 10) * 10; echo "Published in the {$decade}s\n"; // Repeated elements iterate $total = 0.0; foreach ($library->book as $book) { printf("%s (%d) %s %.2f\n", $book->title, $book->year, $book->price['currency'], (float) $book->price); $total += (float) $book->price; } echo 'Total: ', $total, "\n"; // XPath returns an array of matches foreach ($library->xpath('//book[@lang="fr"]/title') as $title) { echo 'French: ', $title, "\n"; } echo count($library->book), " books\n"; // Broken XML: false plus errors, not an exception libxml_use_internal_errors(true); var_dump(simplexml_load_string('<library><book></library>')); echo trim(libxml_get_errors()[0]->message), "\n";
Output
$first->title and $first['id'] print directly because echo casts to string. The var_dump shows what the value really is: object(SimpleXMLElement) wrapping "1965", which is why the decade math casts with (int) first. The loop prints both books and a total of 17.49, and the XPath query finds French: L'Étranger. Malformed XML doesn't throw: simplexml_load_string() returns bool(false), and the reason is in libxml_get_errors(), here Opening and ending tag mismatch: book line 1 and library. Always check for false before using the result.
4Namespaced XML: RSS and Atom feeds
Feeds, SOAP, SVG and Office files put elements in namespaces, and that is where most "SimpleXML returns nothing" questions come from. A prefixed element such as <dc:creator> is not a plain property: switch to its namespace with children($uri). In XPath, register a prefix with registerXPathNamespace() first. Match on the namespace URI, never on the prefix the file happens to use, since another feed can pick a different one.
<?php // RSS with Dublin Core and Media RSS elements in their own namespaces $xml = <<<'XML' <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/"> <channel> <item> <title>Parsing XML</title> <dc:creator>Ada</dc:creator> <media:thumbnail url="https://example.com/a.png" width="120"/> </item> <item> <title>Reading feeds</title> <dc:creator>Linus</dc:creator> <media:thumbnail url="https://example.com/b.png" width="80"/> </item> </channel> </rss> XML; const DC = 'http://purl.org/dc/elements/1.1/'; const MEDIA = 'http://search.yahoo.com/mrss/'; const ATOM = 'http://www.w3.org/2005/Atom'; $rss = simplexml_load_string($xml); // Trap: prefixed elements are not plain properties var_dump(isset($rss->channel->item[0]->creator)); // children($ns) switches to a namespace foreach ($rss->channel->item as $item) { $creator = $item->children(DC)->creator; // Its attributes have no prefix, so read them with attributes() $thumb = $item->children(MEDIA)->thumbnail->attributes(); echo $item->title, ' | ', $creator, ' | ', $thumb['url'], ' (', $thumb['width'], "px)\n"; } // XPath needs each prefix registered first $rss->registerXPathNamespace('dc', DC); $names = array_map('strval', $rss->xpath('//item/dc:creator')); echo implode(', ', $names), "\n"; // Atom puts everything in a default namespace (xmlns="...") $atom = simplexml_load_string(<<<'XML' <feed xmlns="http://www.w3.org/2005/Atom"> <entry><title>First</title><link href="/1"/></entry> <entry><title>Second</title><link href="/2"/></entry> </feed> XML); // Trap: an unprefixed XPath name only matches "no namespace" echo count($atom->xpath('//entry')), " entries without a prefix\n"; // Give the default namespace any prefix and use it $atom->registerXPathNamespace('a', ATOM); foreach ($atom->xpath('//a:entry') as $entry) { echo $entry->title, ' -> ', $entry->link['href'], "\n"; }
Output
isset($item->creator) is bool(false) even though the element is right there. Through children(DC) each item gives its creator, and the thumbnail line shows the second trap: once you are in the media namespace, $thumb['url'] looks for a media-namespaced attribute and comes back empty, so the code reads the unprefixed url and width through attributes(). The Atom feed declares a default namespace, so xpath('//entry') finds 0 entries; registered as a, //a:entry finds both. With DOMXPath the call is registerNamespace() and works the same way.
5Changing a document and writing it back
The same trees can be edited. With Dom\HTMLDocument the methods match the browser: remove(), setAttribute(), classList->add(), append(), and a writable textContent, which escapes what you assign. saveHtml() writes the whole document, or one node when you pass it. On PHP 8.0 to 8.3, DOMElement has the same remove(), append() and setAttribute(), but you find nodes with XPath and there is no classList. For XML, SimpleXML edits values in place, and asXML() writes the result.
<?php $html = <<<'HTML' <!DOCTYPE html> <div id="post"> <h1>Release notes</h1> <script>track()</script> <p>Read the <a href="https://example.org/docs">docs</a> or the <a href="/faq">FAQ</a>.</p> </div> HTML; $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR); $post = $doc->getElementById('post'); // Remove nodes: every <script> foreach ($doc->querySelectorAll('script') as $script) { $script->remove(); } // Set attributes on external links foreach ($post->querySelectorAll('a[href^="http"]') as $link) { $link->setAttribute('rel', 'nofollow noopener'); $link->classList->add('external'); } // Change text, and add a new element (text is escaped for you) $post->querySelector('h1')->textContent = 'Notes for v2 <beta>'; $footer = $doc->createElement('p'); $footer->className = 'meta'; $footer->textContent = 'Updated by Tom & Jerry'; $post->append($footer); // Write it back: one element, or the whole document echo $doc->saveHtml($post), "\n\n"; // XML: SimpleXML edits values, adds children and attributes $items = simplexml_load_string('<items><item id="1">Old</item></items>'); $items->item[0] = 'Renamed'; unset($items->item[0]['id']); $new = $items->addChild('item', htmlspecialchars('Tom & Jerry')); $new->addAttribute('id', '2'); echo $items->asXML(); // For indented output, hand the tree to DOMDocument $dom = dom_import_simplexml($items)->ownerDocument; $dom->formatOutput = true; echo $dom->saveXML();
Output
The script is gone (its blank line stays), only the external link got rel="nofollow noopener" and the external class, and the new heading text came out as Notes for v2 <beta>, so assigning textContent can't inject markup. One SimpleXML trap: the value passed to addChild() is not escaped, and a bare & breaks the value: here (libxml2 2.13.9) addChild('item', 'Tom & Jerry') silently wrote Tom Jerry, and older libxml2 versions print a warning and write an empty element instead. That is why the code passes it through htmlspecialchars(). Assigning to an element, as in $items->item[0] = '...', does escape. asXML() writes everything on one line; for indented output, dom_import_simplexml() hands the tree to DOMDocument with formatOutput on.
6Large XML files: XMLReader
Every parser above loads the whole document into memory first, which fails on a multi-gigabyte export or product feed. XMLReader is a pull parser: it moves through the file one node at a time, so memory stays flat whatever the file size. Its raw API is low-level, so the usual pattern is to stop at each record element and expand() just that one into a small DOM or SimpleXML tree. The example first writes a 50,000-order file with XMLWriter, the matching streaming writer, then reads it back.
<?php // Write a 50,000-order file so there is something big to stream $file = 'orders.xml'; $out = new XMLWriter(); $out->openUri($file); $out->startDocument('1.0', 'UTF-8'); $out->startElement('orders'); for ($i = 1; $i <= 50_000; $i++) { $out->startElement('order'); $out->writeAttribute('id', (string) $i); $out->writeElement('status', $i % 7 === 0 ? 'refunded' : 'paid'); $out->writeElement('total', number_format($i % 100 + 0.5, 2, '.', '')); $out->endElement(); } $out->endElement(); $out->endDocument(); $out->flush(); printf("%.1f MB on disk\n", filesize($file) / 1_000_000); // XMLReader moves through the file one node at a time $reader = XMLReader::open($file); $count = 0; $refunds = 0; $refunded = 0.0; while ($reader->read()) { if ($reader->nodeType !== XMLReader::ELEMENT || $reader->name !== 'order') { continue; } // Expand just this <order> into SimpleXML for easy access $order = simplexml_import_dom($reader->expand(new DOMDocument())); $count++; if ((string) $order->status === 'refunded') { $refunds++; $refunded += (float) $order->total; } if ($count === 1) { echo 'First order id: ', $reader->getAttribute('id'), "\n"; } } $reader->close(); echo "Orders: {$count}\n"; printf("Refunded: %d orders, %.2f\n", $refunds, $refunded);
Output
The file is 3.4 MB on disk, and the loop reads all Orders: 50000 with only one <order> in memory at a time, adding up 7142 orders, 357142.00 in refunds. Check nodeType as well as name: the closing </order> tag has the same name and arrives as an END_ELEMENT node. getAttribute() on the reader reads the current element without expanding it, which is the fastest way when you only need attributes. Newer PHP versions also have XMLReader::fromUri() and XMLReader::fromString().
7Which should you use?
| Method | PHP version | Input | Best for |
|---|---|---|---|
| Dom\HTMLDocument | 8.4+ | HTML5 | Any HTML: scraping, cleaning, CSS selectors |
| DOMDocument + DOMXPath | All | HTML 4 parser, XML | HTML on PHP 8.3 and older; XPath queries |
| simplexml_load_string | All | XML | Reading XML that fits in memory |
| Dom\XMLDocument | 8.4+ | XML | XML with CSS selectors and the modern DOM API |
| XMLReader | All | XML | Files too large to load at once |
| preg_match | Avoid | Text | Not for HTML or XML structure |
Frequently asked questions
How do I fix Class "DOMDocument" not found?
The dom extension is not installed or not enabled; the error reads Uncaught Error: Class "DOMDocument" not found. It is part of PHP but packaged separately on many Linux systems: on Debian and Ubuntu install php-xml (or the versioned one, such as php8.3-xml), which also brings SimpleXML, XMLReader and XMLWriter, then restart PHP-FPM or the web server. Check with php -m or extension_loaded('dom'), and remember the command line and the web server can load different php.ini files.
Why not parse HTML with regex?
HTML is not a regular language. Tags nest, attributes appear in any order with any quoting, values can contain >, comments and scripts contain text that looks like tags, and real pages leave tags unclosed. A preg_match pattern works on the page you tested and fails on the next one. A parser such as Dom\HTMLDocument handles all of it. Regex is fine on a small piece of text you already pulled out with the parser.
How do I load HTML or XML from a file or a URL?
Files have their own loaders: Dom\HTMLDocument::createFromFile($path), DOMDocument::loadHTMLFile(), simplexml_load_file() and XMLReader::open(). For a URL, download the page first with file_get_contents() or cURL and check the HTTP status, then pass the string to createFromString() or loadHTML(). The examples on this page parse strings because the sandbox has no network.
How do I stop DOMDocument warnings like "Tag nav invalid"?
Call libxml_use_internal_errors(true) before loadHTML(). libxml then collects the messages instead of printing warnings; read them with libxml_get_errors() and clear them with libxml_clear_errors(). Avoid @$doc->loadHTML(), which hides real problems too. With Dom\HTMLDocument, pass LIBXML_NOERROR as the second argument to createFromString().
How do I get the innerHTML or outerHTML of an element?
With Dom\HTMLDocument (PHP 8.4+), read $el->innerHTML or $el->outerHTML; innerHTML is also writable. With DOMDocument, $doc->saveHTML($el) returns the outer HTML, and for the inner HTML loop over $el->childNodes and join $doc->saveHTML($child) for each. In XML use saveXML($el) the same way.
Can I use CSS selectors before PHP 8.4?
Not with the built-in classes: DOMDocument only has XPath, getElementsByTagName() and getElementById(). Most CSS selectors translate to XPath, for example #products li is //*[@id="products"]//li. The symfony/css-selector package does that translation for you, and symfony/dom-crawler wraps DOMDocument with a filter() method that takes CSS.