使用 DOMDocument 进行 PHP 编码

2022-08-30 17:27:43
<tag>
Алекс М
</tag>

当我尝试使用 DOMDocument 函数获取以下代码的内容时,它会返回如下内容:

ÐÐ»ÐµÐºÑ Ðœ

我尝试使用mb_convert_encoding,iconv和utf8_encode将DOMDocument编码设置为不同的值(UTF-8,ISO-8859-1),但没有成功。

如何获得“Алекс М”而不是“ÐлÐμÐºÑ Ðœ”?

编辑:输入来自加载了curl的页面。当我将页面内容输出到浏览器时,字符显示正确(所以我怀疑输入是问题所在)。


答案 1

尝试:

$string = file_get_contents('your-xml-file.xml');
$string = mb_convert_encoding($string, 'utf-8', mb_detect_encoding($string));
// if you have not escaped entities use
$string = mb_convert_encoding($string, 'html-entities', 'utf-8'); 
$doc = new DOMDocument();
$doc->loadXML($string);

答案 2

在使用XPath解析DomDocument之后,以及在阅读本文后,我遇到了类似的问题

https://bugs.php.net/bug.php?id=32547

我像这样解决了它

// Workaround because PHP 5.2.x has encoding problems, when we 
// update to PHP 5.3 this line is not necesserry any more
$content = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' . $content;

// Creating new DOM document and loading HTML content
$dom_document = new DOMDocument('1.0', 'UTF-8');
$dom_document->substituteEntities = TRUE;
$dom_document->loadHTML($content);

推荐