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

时间:2022-05-14 15:55:17

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

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

XML Code:

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

PHP代码:

<?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 个解决方案

#1


0  

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:

您的问题是您的字体标记在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];

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...

当然,您的问题是,CDATA将允许使用不合法的XML,比如 <或> ,但这似乎是您最好的选择……

#1


0  

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:

您的问题是您的字体标记在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];

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...

当然,您的问题是,CDATA将允许使用不合法的XML,比如 <或> ,但这似乎是您最好的选择……