your programing

경고 : DOMDocument :: loadHTML () : htmlParseEntityRef : ';'예상

lovepro 2020. 10. 8. 08:27
반응형

경고 : DOMDocument :: loadHTML () : htmlParseEntityRef : ';'예상 엔티티에서


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

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

echo $dom;

던지다

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

경고를 증발 시키려면 다음을 사용할 수 있습니다. 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);

소스를 살펴보면 http://www.somesite.com/HTML로 변환되지 않은 특수 문자를 찾을 수있을 것입니다. 아마도 다음과 같습니다.

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

해야한다

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

$dom->@loadHTML($html);

이것은 올바르지 않습니다. 대신 다음을 사용하십시오.

@$dom->loadHTML($html);

치명적인 오류의 이유는 DOMDocument 에 __toString () 메서드가 없으므로 에코 될 수 없기 때문입니다.

당신은 아마 찾고 있습니다

echo $dom->saveHTML();

두 가지 오류가 있습니다. 두 번째는 $ dom이 문자열이 아니라 객체이므로 "반향"될 수 없기 때문입니다. 첫 번째 오류는로드 할 html 문서의 유효하지 않은 구문으로 인해 발생하는 loadHTML의 경고입니다 (아마도 &가 매개 변수 구분 기호로 사용되고 &가있는 엔티티로 마스크되지 않음).

오류 제어 연산자 "@"( http://www.php.net/manual/en/language.operators.errorcontrol. PHP )

$dom->@loadHTML($html);

에코 (print_r 또는 var_dump로 대체해야 함)에 관계없이 예외가 발생하면 객체는 비어 있어야합니다.

DOMNodeList Object
(
)

해결책

  1. 설정 recovertrue로하고, strictErrorCheckingfalse로

    $content = file_get_contents($url);
    
    $doc = new DOMDocument();
    $doc->recover = true;
    $doc->strictErrorChecking = false;
    $doc->loadHTML($content);
    
  2. 가장 일반적인 오류 소스 인 마크 업의 내용에 PHP의 엔티티 인코딩을 사용합니다.


단순한 것을 대체하십시오

$dom->loadHTML($html);

더 강력한 ...

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

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

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

echo $dom;

이 시도


또 다른 가능한 해결책은

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

나는 이것이 오래된 질문이라는 것을 알고 있지만 HTML에서 잘못된 '&'기호를 수정하지 않으려는 경우. 다음과 유사한 코드를 사용할 수 있습니다.

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

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

참고URL : https://stackoverflow.com/questions/1685277/warning-domdocumentloadhtml-htmlparseentityref-expecting-in-entity

반응형