Accessing tags inside CDATA in XML using PHP

两盒软妹~` 提交于 2019-12-12 18:29:50

问题


I am confused. How can I access tags inside CDATA?

XML Code:

<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 Code:

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

I am using this, but I am getting a blank screen....


回答1:


Your problem is that your font tags are inside of CDATA. Since CDATA stands for "Compiled Data", PHP should treat it as a "block of non-parsed data." It should not (and cannot) let you read those as tags. You'll probably have to do something like:

$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];

Your problem, of course, is that CDATA will let things in which are not valid XML, like < or >, but this seems to be your best option...



来源:https://stackoverflow.com/questions/7065740/accessing-tags-inside-cdata-in-xml-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!