Avviso: DOMDocument :: loadHTML (): htmlParseEntityRef: in attesa di ';' in Entity,


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

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

echo $dom;

lanci

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

Risposte:


149

Per far evaporare l'avvertimento, puoi usare 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);

93

Scommetto che se guardassi l'origine di http://www.somesite.com/te, troverai caratteri speciali che non sono stati convertiti in HTML. Forse qualcosa del genere:

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

Dovrebbe essere

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

3
Solo per espandere questo aspetto, se il carattere & è anche nel testo e non in un attributo HTML, è comunque necessario eseguire l'escape in & amp ;. Il motivo per cui il parser lancia l'errore è perché dopo aver visto un & si aspetta un; per terminare l'entità HTML.
Kyle

22
... e per espandere ulteriormente, chiamare htmlentities()o simili sulla stringa risolverà il problema.
Ben

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

Questo non è corretto, usa questo invece:

@$dom->loadHTML($html);

26
o $ dom-> strictErrorChecking = false;
Tjorriemorrie

8
Questa è una soluzione terribile poiché renderai gli errori su questa linea un incubo per il debug. La soluzione di @ Dewsworld è molto migliore.
Gerry

a cosa serve @?
Francisco Corrales Morales

3
Questa è una soluzione molto sporca e non risolverà tutto.
Mirko Brunner

1
Mentre la tua risposta aggira il problema, la riga "Questo non è corretto" è di per sé errata.
TecBrat

15

Ci sono 2 errori: il secondo è perché $ dom non è una stringa ma un oggetto e quindi non può essere "echo". Il primo errore è un avviso di loadHTML, causato da una sintassi non valida del documento html da caricare (probabilmente una & ( e commerciale) usata come separatore di parametri e non mascherata come entità con &).

Ignori e sopprimi questo messaggio di errore (non l'errore, solo il messaggio!) Chiamando la funzione con l'operatore di controllo errori "@" ( http://www.php.net/manual/en/language.operators.errorcontrol. php )

@$dom->loadHTML($html);

12

La ragione del tuo errore fatale è che DOMDocument non ha un metodo __toString () e quindi non può essere ripetuto.

Probabilmente stai cercando

echo $dom->saveHTML();

10

Indipendentemente dall'eco (che dovrebbe essere sostituito con print_r o var_dump), se viene lanciata un'eccezione l'oggetto dovrebbe rimanere vuoto:

DOMNodeList Object
(
)

Soluzione

  1. Impostato recoversu true e strictErrorCheckingsu false

    $content = file_get_contents($url);
    
    $doc = new DOMDocument();
    $doc->recover = true;
    $doc->strictErrorChecking = false;
    $doc->loadHTML($content);
    
  2. Usa la codifica dell'entità di php sui contenuti del markup, che è una delle fonti di errore più comuni.


1
Nella prima soluzione hai scritto dom invece di doc.
Máthé Endre-Botond

questo ha funzionato per me ho aggiunto solo $ content = mb_convert_encoding ($ content, 'HTML-ENTITIES', 'UTF-8');
Jacek Pietal

8

sostituire il semplice

$dom->loadHTML($html);

con il più robusto ...

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;
    }

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

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

echo $dom;

prova questo


3

Un'altra possibile soluzione è

$sContent = htmlspecialchars($sHTML);
$oDom = new DOMDocument();
$oDom->loadHTML($sContent);
echo html_entity_decode($oDom->saveHTML());

Questo non funzionerà. Secondo php.net/manual/en/function.htmlspecialchars.php , anche tutti i caratteri speciali HTML sono sottoposti a escape. Prendi ad esempio questo pezzo di codice HTML <span>Hello World</span>. Eseguire questo in htmlspecialcharsprodurrà &lt;span&gt;Hello World&lt/span&gt;che non è più HTML. DOMDocument :: loadHTML non lo tratterà più come HTML ma come una stringa.
Twisted Whisper

Questo funziona per me:$oDom = new DOMDocument(); $oDom->loadHTML($sHTML); echo html_entity_decode($oDom->saveHTML());
Bartłomiej Jakub Kwiatek

3

So che questa è una vecchia domanda, ma se vuoi correggere i segni "&" malformati nel tuo HTML. Puoi usare un codice simile a questo:

$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.
        }
    }
}

0

Un'altra possibile soluzione è, forse il tuo file è di tipo ASCII, basta cambiare il tipo dei tuoi file.


-1

Anche dopo questo il mio codice funziona correttamente, quindi ho appena rimosso tutti i messaggi di avviso con questa istruzione alla riga 1.

<?php error_reporting(E_ERROR); ?>
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.