为什么DOM会改变编码?

Ric*_*nop 20 php dom utf-8

$string = file_get_contents('http://example.com');

if ('UTF-8' === mb_detect_encoding($string)) {
    $dom = new DOMDocument();
    // hack to preserve UTF-8 characters
    $dom->loadHTML('<?xml encoding="UTF-8">' . $string);
    $dom->preserveWhiteSpace = false;
    $dom->encoding = 'UTF-8';
    $body = $dom->getElementsByTagName('body');
    echo htmlspecialchars($body->item(0)->nodeValue);
}
Run Code Online (Sandbox Code Playgroud)

这会将所有UTF-8字符更改为Å,¾,¤和其他垃圾.有没有其他方法如何保存UTF-8字符?

不要发布答案告诉我确保我输出它作为UTF-8,我确定我是.

提前致谢 :)

and*_*ott 40

我最近遇到了类似的问题,并最终找到了这个解决方法 - 在加载html之前将所有非ascii字符转换为html实体

$string = mb_convert_encoding($string, 'HTML-ENTITIES', "UTF-8");
$dom->loadHTML($string);
Run Code Online (Sandbox Code Playgroud)