Dom\HTMLDocument::createFromString

(PHP 8 >= 8.4.0)

Dom\HTMLDocument::createFromStringAnaliza un documento HTML a partir de un string

Descripción

public static Dom\HTMLDocument::createFromString(string $source, int $options = 0, ?string $overrideEncoding = null): Dom\HTMLDocument

Analiza un documento HTML a partir de un string, según la norma vigente.

Parámetros

source
El string que contiene el HTML a analizar.
options

Bitwise OR of the libxml option constants.

It is also possible to pass Dom\HTML_NO_DEFAULT_NS to disable the use of the HTML namespace and the template element. This should only be used if the implications are properly understood.
overrideEncoding
The encoding that the document was created in. If not provided, it will attempt to determine the encoding that is most likely used.

Valores devueltos

El documento analizado en forma de una instancia de Dom\HTMLDocument.

Errores/Excepciones

  • Throws a ValueError if options contains an invalid option.
  • Throws a ValueError if overrideEncoding is an unknown encoding.

Ejemplos

Ejemplo #1 Ejemplo de Dom\HTMLDocument::createFromString()

Analiza un documento de ejemplo.

<?php
$dom
= Dom\HTMLDocument::createFromString(<<<'HTML'
<!DOCTYPE html>
<html>
<body>
<p>Hello, world!</p>
</body>
</html>
HTML);
echo
$dom->saveHtml();
?>

El resultado del ejemplo sería:

<!DOCTYPE html><html><head></head><body>
    <p>Hello, world!</p>

</body></html>

Notas

Nota: Whitespace in the html and head tags is not considered significant and may lose formatting.

Ver también

add a note

User Contributed Notes 1 note

up
4
kawewong at gmail dot com
5 months ago
To load HTML without doctype, html, body elements use `LIBXML_HTML_NOIMPLIED` flag.

<?php
$html
= <<<EOT
<div class="row">
<div class="col"><h1 id="heading" class="col1-heading">Hello</h1></div>
<div class="col"><p class="paragraph">Hello world.</p>
</div>
EOT;
$doc = \DOM\HTMLDocument::createFromString($html, LIBXML_HTML_NOIMPLIED);
echo
htmlspecialchars($doc->saveHTML(), ENT_QUOTES);
?>
To Top