109
$html = file_get_contents("http://www.somesite.com/");

$dom = new DOMDocument();
$dom->loadHTML($html);

echo $dom;

throws

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,
Catchable fatal error: Object of class DOMDocument could not be converted to string in test.php on line 10
0

12 Answers 12

181

To evaporate the warning, you can use libxml_use_internal_errors(true)

// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');

// set error level
$internalErrors = libxml_use_internal_errors(true);

// load HTML
$document->loadHTML($html);

// Restore error level
libxml_use_internal_errors($internalErrors);
0
100

I would bet that if you looked at the source of http://www.somesite.com/ you would find special characters that haven't been converted to HTML. Maybe something like this:

<a href="/script.php?foo=bar&hello=world">link</a>

Should be

<a href="/script.php?foo=bar&amp;hello=world">link</a>
2
  • 8
    Just to expand on this, if the & character is even in text and not an HTML attribute, it still needs to be escaped to &amp;. The reason the parser is throwing the error is because after seeing an & it's expecting a ; to terminate the HTML entity.
    – Kyle
    Jul 26, 2012 at 16:17
  • 25
    ...and to expand further, calling htmlentities() or similar on the string will fix the problem.
    – Ben
    Jun 26, 2013 at 6:16
56
$dom->@loadHTML($html);

This is incorrect, use this instead:

@$dom->loadHTML($html);
6
  • 27
    or $dom->strictErrorChecking = false; Jul 28, 2011 at 10:42
  • 9
    This is a terrible solution as you will make errors on this line a nightmare to debug. @Dewsworld's solution is much better.
    – Gerry
    Aug 1, 2013 at 2:32
  • what is the @ for ? Feb 12, 2014 at 22:12
  • 4
    This is a very dirty solution and this won´t fix everything. Dec 8, 2015 at 13:22
  • 2
    While your answer will work around the problem, the line "This is incorrect" is, itself, incorrect.
    – TecBrat
    Feb 25, 2017 at 22:24
16

There are 2 errors: the second is because $dom is no string but an object and thus cannot be "echoed". The first error is a warning from loadHTML, caused by invalid syntax of the html document to load (probably an & (ampersand) used as parameter separator and not masked as entity with &).

You ignore and supress this error message (not the error, just the message!) by calling the function with the error control operator "@" (http://www.php.net/manual/en/language.operators.errorcontrol.php )

@$dom->loadHTML($html);
12

The reason for your fatal error is DOMDocument does not have a __toString() method and thus can not be echo'ed.

You're probably looking for

echo $dom->saveHTML();
11

Regardless of the echo (which would need to be replaced with print_r or var_dump), if an exception is thrown the object should stay empty:

DOMNodeList Object
(
)

Solution

  1. Set recover to true, and strictErrorChecking to false

    $content = file_get_contents($url);
    
    $doc = new DOMDocument();
    $doc->recover = true;
    $doc->strictErrorChecking = false;
    $doc->loadHTML($content);
    
  2. Use php's entity-encoding on the markup's contents, which is a most common error source.

2
  • 1
    On the first solution you wrote dom instead of doc. Dec 26, 2011 at 20:38
  • this worked for me I only added $content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ); Sep 24, 2014 at 10:02
10

replace the simple

$dom->loadHTML($html);

with the more robust ...

libxml_use_internal_errors(true);

if (!$DOM->loadHTML($page))
    {
        $errors="";
        foreach (libxml_get_errors() as $error)  {
            $errors.=$error->message."<br/>";
        }
        libxml_clear_errors();
        print "libxml errors:<br>$errors";
        return;
    }
9
$html = file_get_contents("http://www.somesite.com/");

$dom = new DOMDocument();
$dom->loadHTML(htmlspecialchars($html));

echo $dom;

try this

6

I know this is an old question, but if you ever want ot fix the malformed '&' signs in your HTML. You can use code similar to this:

$page = file_get_contents('http://www.example.com');
$page = preg_replace('/\s+/', ' ', trim($page));
fixAmps($page, 0);
$dom->loadHTML($page);


function fixAmps(&$html, $offset) {
    $positionAmp = strpos($html, '&', $offset);
    $positionSemiColumn = strpos($html, ';', $positionAmp+1);

    $string = substr($html, $positionAmp, $positionSemiColumn-$positionAmp+1);

    if ($positionAmp !== false) { // If an '&' can be found.
        if ($positionSemiColumn === false) { // If no ';' can be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // Replace straight away.
        } else if (preg_match('/&(#[0-9]+|[A-Z|a-z|0-9]+);/', $string) === 0) { // If a standard escape cannot be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // This mean we need to escape the '&' sign.
            fixAmps($html, $positionAmp+5); // Recursive call from the new position.
        } else {
            fixAmps($html, $positionAmp+1); // Recursive call from the new position.
        }
    }
}
3

Another possibile solution is

$sContent = htmlspecialchars($sHTML);
$oDom = new DOMDocument();
$oDom->loadHTML($sContent);
echo html_entity_decode($oDom->saveHTML());
2
  • This will not work. According to php.net/manual/en/function.htmlspecialchars.php, all html special characters are escaped too. Take for example this piece of HTML code <span>Hello World</span>. Running this into htmlspecialchars will produce &lt;span&gt;Hello World&lt/span&gt; which isn't HTML anymore. DOMDocument::loadHTML will not treat it as HTML anymore but as a string. Oct 23, 2013 at 10:48
  • This works for me: $oDom = new DOMDocument(); $oDom->loadHTML($sHTML); echo html_entity_decode($oDom->saveHTML()); Mar 31, 2016 at 9:50
0

Another possibile solution is,maybe your file is ASCII type file,just change the type of your files.

-1

Even after this my code is working fine , so i just removed all warning messages with this statement at line 1 .

<?php error_reporting(E_ERROR); ?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.