【发布时间】:2011-10-30 10:41:43
【问题描述】:
我需要从一些 CRM 软件中获取 XML 文件。
XML 文件编码为 UTF-8,但存在一些“奇怪”字符,由于这些字符,我无法解析带有 simple_xml 的文件。
例如:
<ROW ART_LIB="CAT NxA1 2008" />
存在“xA1”字符。它是什么,如何将其编码为“好”字符?
要解析的好结果是:
<ROW ART_LIB="CAT N° 2008" />
所以,实际上,为了解析 XML 文件,我这样做了:
$fichier = utf8_encode(file_get_contents($inputfileName));
$xmlInput = simplexml_load_string($fichier);
我该如何解决?
感谢 Jason Coco 的帮助,我已经解决了这个问题:
function mac_roman_to_iso($string)
{
return strtr($string,
"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa1\xa4\xa6\xa7\xa8\xab\xac\xae\xaf\xb4\xbb\xbc\xbe\xbf\xc0\xc1\xc2\xc7\xc8\xca\xcb\xcc\xd6\xd8\xdb\xe1\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf8\xfc\xd2\xd3\xd4\xd5Ð",
"\xc4\xc5\xc7\xc9\xd1\xd6\xdc\xe1\xe0\xe2\xe4\xe3\xe5\xe7\xe9\xe8\xea\xeb\xed\xec\xee\xef\xf1\xf3\xf2\xf4\xf6\xf5\xfa\xf9\xfb\xfc\xb0\xa7\xb6\xdf\xae\xb4\xa8\xc6\xd8\xa5\xaa\xba\xe6\xf8\xbf\xa1\xac\xab\xbb\xa0\xc0\xc3\xf7\xff\xa4\xb7\xc2\xca\xc1\xcb\xc8\xcd\xce\xcf\xcc\xd3\xd4\xd2\xda\xdb\xd9\xaf\xb8\x22\x22\x27\x27-");
}
$fichier = mac_roman_to_iso(file_get_contents($fichier));
$xmlInput = simplexml_load_string(utf8_encode($fichier));
然后,使用 iconv() 将值从 ISO-8859-1 编码为 UTF-8。
【问题讨论】:
-
您是否 100% 确定远程文件的编码是 UTF-8?如果将其视为 ISO-8859-1 会发生什么,它看起来会更好吗?如果远程文件提供了错误编码的数据,最好的办法是尝试让他们修复它(或尽可能覆盖编码)
-
如果你确定它已经被
UTF-8-encoded,你为什么还要utf8_encode它。也许`$fichier = utf8_decode(file_get_contents($inputfileName));'会成功吗? -
是的,它是 UTF-8。当我将它转换为记事本++时,我明白了:
-
¡ 是 xA1 的字符,例如ANSI, latin1, ... 文档中是否还有其他字符不是 ASCII (0-127) 并且也不会导致 simplexml_load_string() 错误?
-
我同意@Pekka ... xA1 没有任何意义,根本不是有效的 UTF-8。它的 latin-1 编码是 0xB0,即 UTF-8 中的 0xC2 0xB0。
标签: php xml utf-8 simplexml xml-parsing