特殊字符的 XML 解析,例如 PHP 中的“&”符号


xml parsing of special characters, such as '&' symbol in php

我无法解析带有特殊字符的xml文件中的特殊字符(我无法编辑该文件),例如php中的"&"符号。

这是一个示例xml代码片段,我尝试使其在php中工作并显示。

<?xml version="1.0" encoding="ISO-8859-1"?> <node> <test>Don't & forget me this weekend!</test> </node>

任何帮助都非常感谢:)

要使用&特殊字符,代码&amp;

另请查看 : http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

在那个极端情况下:

str_replace("&", "&amp;", $xml);

会使其正确解析。不幸的是,如果您有一个大于或小于符号未转义:

<?xml version="1.0" encoding="ISO-8859-1"?>
<node>
  <test>Oh my < Goodness </test>
</node>

str_replace是行不通的。现在你可以做正则表达式来测试类似 <[a-zA-Z] 的东西,但接下来是:

<?xml version="1.0" encoding="ISO-8859-1"?>
<node>
  <test>Oh my<Goodness </test>
</node>

所以这基本上会扼杀你使用正则表达式的机会。

我尝试使用SimpleXML,DOM,XmlReader解析您的XML,并尝试了许多libxml属性,但没有任何效果。

所以简而言之,可能性对你不利。提供程序需要生成正确的 XML。