Cannot parse CDATA with SimpleXML

2019-07-06 21:24发布

I have the following XML code:

<para>
      <![CDATA[
        <?php
        $data = '<?xml version="1.0"?>
        <root>content</root>';
        $sxe = simplexml_load_string($data);
        var_dump($sxe);
        ?>
      ]]>
    </para>

I want to parse the CDATA section to take this result:

Content:
<?php
$data = '<?xml version="1.0"?>
<root>content</root>';
$sxe = simplexml_load_string($data);
var_dump($sxe);
?>

I use the following but it doesn't work.

$xml='sxml.xml';
$book = simplexml_load_file($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

$para = $book->chapter->para[1];
print "Content: ".$para."<br>";

foreach($para AS $node) {
    print "Iter Content: ".$node."<br>";    
}

This results in:

Content: 


        content';
        $sxe = simplexml_load_string($data);
        var_dump($sxe);
        ?>

In phpinfo() it shows that libxml is enabled and active. Any help? Thanks in advance

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-06 21:48

You should encode the special characters using htmlspecialchars

For example: print "Content: ".htmlspecialchars($para)."<br>";

查看更多
登录 后发表回答