gpt4 book ai didi

php - 为什么 DOM 会改变编码?

转载 作者:IT王子 更新时间:2023-10-28 23:56:31 27 4
gpt4 key购买 nike

$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 字符?

不要发布答案告诉我确保我将其输出为 UTF-8,我确定我是。

提前致谢:)

最佳答案

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

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

关于php - 为什么 DOM 会改变编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236889/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com