【发布时间】:2013-08-28 12:32:39
【问题描述】:
我正在解析一个包含 UTF-8 编码字符的 XML-Feed,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<value>Ströng</value>
</root>
解析这个文件返回一个格式错误的Ströng:
$file = file_get_contents($path);
print_r($file);
使用$xml = simplexml_load_file($path); 会产生相同的结果。
现在我尝试使用utf8_encode() 函数来纠正这样的字符编码:
$file = utf8_encode(file_get_contents($path));
print_r($file);
但现在内容的格式错误更严重:Ströng。这是为什么呢?
如何正确解析 UTF8 格式的 XML?
更新:
mb_detect_encoding($file) 返回:UTF-8 和 utf8_decode() 返回Str?ng。
到目前为止,一切似乎都是正确的,但事实并非如此?
【问题讨论】:
-
因为你需要utf_decode,或者把你的php脚本做成utf8
-
file_get_contents对编码执行 nothing。您只是没有告诉浏览器正确处理它。见UTF-8 all the way through 和What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text。 -
utf8_decode()返回Str?ng -
mb_detect_encoding()返回UTF-8,应该没问题吧?
标签: php string parsing encoding utf-8