使用PHP在XML中访问CDATA中的标记


Accessing tags inside CDATA in XML using PHP

我很困惑。如何访问CDATA内的标签?

XML代码:

<body>
<block>
<![CDATA[ 
     <font color="#FFCC53" size="+6"><b>Latest News Updates</b></font>
     <font color="#AAAAAA">HTML Formatted Text Fields</font>            
]]>                         
</block>
</body>
PHP代码:

<?php
     $xml = simplexml_load_file("main.xml");
     print (  $xml->smallTextList[0]->item[0]->textBody[0]->font[0] ) ;
?>

我正在使用这个,但我得到一个空白屏幕....

您的问题是您的字体标签在CDATA的内。由于CDATA代表"已编译数据",PHP应该将其视为"未解析数据块"。它不应该(也不可能)让你把它们当作标签来读。您可能需要这样做:

$xml = simplexml_load_file("main.xml");
$inner = simplexml_load_string( 
 '<fk>' . // you have to wrap the CDATA in a tag, otherwise it will break.
      // not sure about asXML. You may be able to get away without it.
      $xml->block[0]->asXML() . 
 '</fk>'
 );
print $inner->font[0];

你的问题,当然,是CDATA将允许的东西不是有效的XML,如<>,但这似乎是你最好的选择…