Choose Valid Options for PHP Dom HTMLDocument

Last updated: December 3, 2026.

When Dom\HTMLDocument::createFromString() rejects an options mask, start with 0 and add only flags documented for that method. Flags accepted by an XML parser or the older HTML parser can differ.

<?php

$html = '<!doctype html><title>Notes</title><main>Résumé</main>';
$document = Dom\HTMLDocument::createFromString($html, 0, 'UTF-8');
$main = $document->querySelector('main');

echo $main?->textContent, PHP_EOL; // Résumé

Choose an option by the result you need

The example uses PHP 8.4 or later with DOM enabled. The third argument explicitly selects UTF-8 because the application knows the input encoding. For arbitrary input, preserve its real encoding information or let detection run rather than assuming every source is UTF-8.

For a complete page, start with default parsing and allow the parser to build the usual document structure. Use LIBXML_HTML_NOIMPLIED only when you specifically want to avoid implied wrapper elements and have checked the resulting tree. The method’s documented option list also includes flags for compact storage, parse diagnostics and opting out of the default HTML namespace. Read the effect of each flag before copying an old mask.

Separate a rejected option from a parsing problem

A ValueError about flags means the arguments were rejected. Hiding parse diagnostics will not fix that. Remove the incompatible flag, run the smallest representative input and inspect the DOM before adding another option.

Check a text node containing accented characters and a selector that crosses the part of the document affected by the option. If an older workflow depended on specific wrappers or namespaces, test those properties directly. Parsing constructs a tree and does not sanitize HTML for output.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov