2011-06-01 168 views
1

我使用PHP来生成XML文件。我使用下面的一些代码来避免错误。如何解决“simplexml_load_file()解析器错误:实体'nbsp'未定义”?

$str = str_ireplace(array('<','>','&','\'','"'),array('&lt;','&gt;','&amp;','&apos;','&quot;'),$str); 

但仍导致错误。

simplexml_load_file() [function.simplexml-load-file] *[file name]* parser error : Entity 'nbsp' not defined in *[file name] [line]* 

错误文本的位置:

Dallas&nbsp;&nbsp;Dallas() is the third-largest city in Texas and the ninth-largest in the United States. 

在IE8,它似乎在()故障。那么我应该注意到多少个符号?

+0

' '在默认情况下未在XML中定义。也许只是用一个空间替换它就足够了? – 2011-06-01 23:14:11

+0

你说你使用PHP来*生成* XML文件;你在用什么?如果你使用的是正确的工具,它应该为你处理这些实体... – 2011-06-01 23:16:35

回答

4

&nbsp;是一个HTML实体,但不存在于XML中。

要么摆脱它(你不是说它来自哪里,所以很难给出更具体的建议),或者将你的HTML数据包装在CDATA块中,以便解析器忽略它们。

+0

所以如果我使用CDATA,我还需要使用'str_ireplace'吗?谢谢。 – cj333 2011-06-01 23:22:58

+0

@ cj333不,你不应该使用str_ireplace – 2013-11-29 12:58:38

3

HTML特定实体 - 在这种情况下&nbsp; - 不是有效的xml实体,这就是simplexml所抱怨的;它将该文件读取为xml(而不是html)并查找无效的实体。您需要将HTML实体转换回其字符表示第一个(可以使用html_entity_decode()做到这一点)

$str = "some string containing html"; 
// this line will convert back html entities to regular characters 
$str = html_entity_decode($str, ...); 
// now convert special character to their xml entities 
$str = str_ireplace(array('<','>','&','\'','"'),array('&lt;','&gt;','&amp;','&apos;','&quot;'),$str); 

save_to_xml($str); 

请注意,如果你将其保存在XML之前用你的字符串ヶ辆(),那么这就是您的问题的来源(因为您正在将html字符转换为其各自的html实体,而这些实体不会被simplexml识别为xml实体)。

// this won't work, the html entities it will uses are not valid xml entities 
$str = htmlentities($str, ...) 

save_to_xml($str); 

如果你有麻烦了解它,认为它是两个不同的语言,如西班牙语(HTML)和英语(XML),西班牙语( )有效的字并不意味着它也是有效的英语,不管这两种语言的相似之处。

相关问题