使用 DOMDocument 进行 PHP 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2142120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:13:18  来源:igfitidea点击:

PHP encoding with DOMDocument

phpdomcharacter-encoding

提问by Olivier Lalonde

<tag>
Алекс М
</tag>

When I try to get the content of the following code using DOMDocument functions, it returns something like:

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

DD?DμDo? D?

I've tried setting DOMDocument encoding to different values (UTF-8, ISO-8859-1), using mb_convert_encoding, iconv and utf8_encode but without success.

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

How can I get "Алекс М" instead of "DD?DμDo? D?" ?

我怎样才能得到“Алекс М”而不是“DD?DμDo?D?” ?

EDIT: The input is coming from a page loaded with curl. When I output the page content to my browser, the characters are displayed correctly (so I doubt the input is the problem).

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

回答by Dmytro Zavalkin

Try:

尝试:

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

回答by Nemke

I had a similar problem after using XPath to parse DomDocument, and after reading this

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

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

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

I solved it like this

我是这样解决的

// 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);

回答by Casey

Add xml header to you tags - try this:

将 xml 标头添加到您的标签 - 试试这个:

$a = new DOMDocument ();
$a->loadXml ('<?xml version="1.0" encoding="UTF-8"?><tag>Алекс М</tag>');
print htmlspecialchars ($a->saveXml ());