php - 错误的字符编码 DOMDocument php

标签 php character-encoding domdocument

我有一些 html 内容,它的所有文本都是波斯语! 我想通过方法 DOMDocument::loadHTML($html) 将此内容提供给 DOMDocument 来做一些事情,然后通过 DOMDocument::saveHTML() 将其返回......但是显示字符时存在问题:-( 例如,“سلام”更改为“سلام”,即使我将脚本文件编码更改为 UTF-8,但它不起作用。

<?php
$html = "<html><meta charset='utf-8' /> سلام</html>";

$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadHTML($html);
print $html; // output : سلام
print $doc->saveHTML(); // output : سلام
print $doc->saveHTML($doc->documentElement); // output : سÙاÙ
?>

更新:根据 friend 的指示,我使用了 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); 它奏效了!

最佳答案

告诉 XML 解析器正在读取的数据是 UTF-8 编码的:

<?php

// original input (unknown encoding)
$html = '<html>سلام</html>';

$doc = new DOMDocument();

// specify the input encoding
$doc->loadHTML('<?xml encoding="utf-8"?>' . $html);

// specify the output encoding
$doc->encoding = 'utf-8';

// output: <html><body><p>سلام</p></body></html>
print $doc->saveHTML($doc->documentElement);

关于php - 错误的字符编码 DOMDocument php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12034235/

相关文章:

javascript - 在 Ajax 中发送复选框值

php - 存储数据的奇怪字符编码,旧脚本显示它们很好,新脚本却没有

php - 如何为 XPath 查询选择多个属性

php - PHP中有没有办法访问压缩的RTF并输出RTF代码

php - 为什么这个简单的 php 脚本会泄漏内存?

php preg_match 可选子模式

Mysql保加利亚语言,字符集

php - 如何使用 PHP 修复损坏的编码单词

php - 为什么 'child' 和 'descendant' 在此 domdocument() 查询中给出相同的结果?

php - 将 DOMDocument 根元素附加到另一个 DOMDocument