为什么DOM改变编码? [英] Why Does DOM Change Encoding?

查看:228
本文介绍了为什么DOM改变编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

This changes all UTF-8 characters to Å, ¾, ¤ and other rubbish. Is there any other way how to preserve UTF-8 characters?

不要发布回答告诉我确定我输出为UTF-8,我确定我是。

Don't post answers telling me to make sure I am outputting it as UTF-8, I made sure I am.

提前感谢:)

推荐答案

最近发现了类似的问题,最终发现这个解决方法 - 在加载html之前,将所有的非ASCII字符转换为html实体

I had similar problems recently, and eventually found this workaround - convert all the non-ascii characters to html entities before loading the html

$string = mb_convert_encoding($string, 'HTML-ENTITIES', "UTF-8");
$dom->loadHTML($string);

这篇关于为什么DOM改变编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆