PHP 7.0.6 Released

DOMDocument::loadHTML

(PHP 5, PHP 7)

DOMDocument::loadHTML Charge du code HTML à partir d'une chaîne de caractères

Description

public bool DOMDocument::loadHTML ( string $source [, int $options = 0 ] )

Cette fonction analyse un document HTML contenu dans la chaîne source. Contrairement au XML, le HTML n'a pas besoin d'être bien formé pour être chargé. Cette fonction peut aussi être appelée statiquement pour charger et créer un objet DOMDocument. L'appel statique peut être utilisé lorsque vous n'avez besoin de configurer aucune propriété de DOMDocument avant le chargement.

Liste de paramètres

source

La chaîne HTML.

options

Depuis PHP 5.4.0 et Libxml 2.6.0, vous pouvez également utiliser le paramètre options pour spécifier des paramètres additionnels à Libxml.

Valeurs de retour

Cette fonction retourne TRUE en cas de succès ou FALSE si une erreur survient. Si appelée statiquement, retourne un DOMDocument ou FALSE si une erreur survient.

Erreurs / Exceptions

Si une chaîne vide est passée comme paramètre source, une alerte sera générée. Cette alerte n'est pas générée par libxml, et ne peut être gérée en utilisant les fonctions de gestion d'erreur de libxml.

Cette méthode peut être appelée statiquement, mais enverra une erreur E_STRICT.

Bien que le HTML mal-formé devrait se charger avec succès, cette fonction peut générer une alerte de type E_WARNING lorsqu'elle rencontre une mauvaise balise. Les fonctions de gestion des erreurs libxml peuvent être utilisées pour gérer ces erreurs.

Exemples

Exemple #1 Création d'un document

<?php
$doc 
= new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo 
$doc->saveHTML();
?>

Historique

Version Description
5.4.0 Ajout du paramètre options.

Voir aussi

add a note add a note

User Contributed Notes 13 notes

up
58
mdmitry at gmail dot com
6 years ago
You can also load HTML as UTF-8 using this simple hack:

<?php

$doc
= new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $html);

// dirty fix
foreach ($doc->childNodes as $item)
    if (
$item->nodeType == XML_PI_NODE)
       
$doc->removeChild($item); // remove hack
$doc->encoding = 'UTF-8'; // insert proper

?>
up
35
Shane Harter
6 years ago
DOMDocument is very good at dealing with imperfect markup, but it throws warnings all over the place when it does.

This isn't well documented here. The solution to this is to implement a separate aparatus for dealing with just these errors.

Set libxml_use_internal_errors(true) before calling loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions.

You can find more info here http://www.php.net/manual/en/ref.libxml.php
up
11
bigtree at DONTSPAM dot 29a dot nl
11 years ago
Pay attention when loading html that has a different charset than iso-8859-1. Since this method does not actively try to figure out what the html you are trying to load is encoded in (like most browsers do), you have to specify it in the html head. If, for instance, your html is in utf-8, make sure you have a meta tag in the html's head section:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>

If you do not specify the charset like this, all high-ascii bytes will be html-encoded. It is not enough to set the dom document you are loading the html in to UTF-8.
up
8
Errol
7 years ago
It should be noted that when any text is provided within the body tag
outside of a containing element, the DOMDocument will encapsulate that
text into a paragraph tag (<p>).

For example:
<?php
$doc
= new DOMDocument();
$doc->loadHTML("<html><body>Test<br><div>Text</div></body></html>");
echo
$doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>Test<br></p>
<div>Text</div>
</body></html>

while:
<?php
$doc
= new DOMDocument();
$doc->loadHTML(
   
"<html><body><i>Test</i><br><div>Text</div></body></html>");
echo
$doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<i>Test</i><br><div>Text</div>
</body></html>
up
17
hanhvansu at yahoo dot com
9 years ago
When using loadHTML() to process UTF-8 pages, you may meet the problem that the output of dom functions are not like the input. For example, if you want to get "Cạnh tranh", you will receive "Cạnh tranh".  I suggest we use mb_convert_encoding before load UTF-8 page :
<?php
    $pageDom
= new DomDocument();   
   
$searchPage = mb_convert_encoding($htmlUTF8Page, 'HTML-ENTITIES', "UTF-8");
    @
$pageDom->loadHTML($searchPage);

?>
up
8
cake at brothercake dot com
3 years ago
Be aware that this function doesn't actually understand HTML -- it fixes tag-soup input using the general rules of SGML, so it creates well-formed markup, but has no idea which element contexts are allowed.

For example, with input like this where the first element isn't closed:

    <span>hello <div>world</div>

loadHTML will change it to this, which is well-formed but invalid:

    <span>hello <div>world</div></span>
up
3
romain dot lalaut at laposte dot net
9 years ago
Note that the elements of such document will have no namespace even with <html xmlns="http://www.w3.org/1999/xhtml">
up
2
jamesedwardcooke+php at gmail dot com
7 years ago
Using loadHTML() automagically sets the doctype property of your DOMDocument instance(to the doctype in the html, or defaults to 4.0 Transitional). If you set the doctype with DOMImplementation it will be overridden.

I assumed it was possible to set it and then load html with the doctype I defined(in order to decide the doctype at runtime), and ran into a huge headache trying to find out where my doctype was going. Hopefully this helps someone else.
up
1
xuanbn at yahoo dot com
8 years ago
If you use loadHTML() to process utf HTML string (eg in Vietnamese), you may experience result in garbage text, while some files were OK. Even your HTML already have meta charset  like

  <meta http-equiv="content-type" content="text/html; charset=utf-8">

I have discovered that, to help loadHTML() process utf file correctly, the meta tag should come first, before any utf string appear. For example, this HTML file

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title> Vietnamese - Tiếng Việt</title>
  </head>
<body></body>
</html>

will be OK with loadHTML() when <meta> tag appear <title> tag.

But the file below will not regcornize by loadHTML() because <title> tag contains utf string appear before <meta> tag.

<html>
<head>
    <title> Vietnamese - Tiếng Việt</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
  </head>
<body></body>
</html>
up
1
piopier
6 years ago
Here is a function I wrote to capitalize the previous remarks about charset problems (UTF-8...) when using loadHTML and then DOM functions.
It adds the charset meta tag just after <head> to improve automatic encoding detection, converts any specific character to an html entity, thus PHP DOM functions/attributes will return correct values.

<?php
mb_detect_order
("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
function
loadNprepare($url,$encod='') {
       
$content        = file_get_contents($url);
        if (!empty(
$content)) {
                if (empty(
$encod))
                       
$encod  = mb_detect_encoding($content);
               
$headpos        = mb_strpos($content,'<head>');
                if (
FALSE=== $headpos)
                       
$headpos= mb_strpos($content,'<HEAD>');
                if (
FALSE!== $headpos) {
                       
$headpos+=6;
                       
$content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos);
                }
               
$content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod);
        }
       
$dom = new DomDocument;
       
$res = $dom->loadHTML($content);
        if (!
$res) return FALSE;
        return
$dom;
}
?>

NB: it uses mb_strpos/mb_substr instead of mb_ereg_replace because that seemed more efficient with huge html pages.
up
0
fr at felix-riesterer dot de
2 months ago
Remember: If you use an HTML5 doctype and a meta element like so

<meta charset=utf-8">

your HTML code will get interpreted as ISO-8859-something and non-ASCII chars will get converted into HTML entities. However the HTML4-like version will work (as has been pointed out 10 years ago by "bigtree at 29a"):

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
up
0
finkenb2 at mail dot lib dot msu dot edu
6 months ago
Warning:  This does not function well with HTML5 elements such as SVG.  Most of the advice on the Web is to turn off errors in order to have it work with HTML5.
up
0
Alex
6 years ago
Beware of the "gotcha" (works as designed but not as expected): if you use loadHTML, you cannot validate the document. Validation is only for XML. Details here: http://bugs.php.net/bug.php?id=43771&edit=1
To Top