由于该标记<! - [CDATA []] - >,无法从xml文件中读取数据

时间:2012-10-25 07:03:44

标签: php xml

的test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0"
    xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:wp="http://wordpress.org/export/1.2/"
>

    <item>
        <title>Hello world!</title>
        <link>http://localhost/wordpress/?p=1</link>
        <category><![CDATA[Uncategorized]]></category>
        <HEADLINE><![CDATA[Does Sleep Apnea Offer Some Protection During Heart Attack?]]></HEADLINE>
    </item>
</rss>

我使用该代码读取xml文件

    <?php
      if (file_exists('test.xml')) {
        $xml = simplexml_load_file('test.xml');
          echo "<pre>";
          print_r($xml);
          echo "</pre>";
      } else {
         exit('Failed to open test.xml.');
         }
     ?>

输出

      SimpleXMLElement Object
 (
 [@attributes] => Array
    (
        [version] => 2.0
    )

[item] => SimpleXMLElement Object
    (
        [title] => Hello world!
        [link] => http://localhost/wordpress/?p=1
        [category] => SimpleXMLElement Object
            (
            )

        [HEADLINE] => SimpleXMLElement Object
            (
            )

    )

 )

但我在xml

中遇到问题
        <category><![CDATA[Uncategorized]]></category>
    <HEADLINE><![CDATA[Does Sleep Apnea Offer Some Protection During Heart Attack?]]></HEADLINE>

 to read data bcoz of it <![CDATA[]] in category and HEADLINE

我需要输出

        SimpleXMLElement Object
   (
 [@attributes] => Array
    (
        [version] => 2.0
    )

[item] => SimpleXMLElement Object
    (
        [title] => Hello world!
        [link] => http://localhost/wordpress/?p=1
        [category] => Uncategorized
        [HEADLINE] => Does Sleep Apnea Offer Some Protection During Heart Attack?
    )

 )

3 个答案:

答案 0 :(得分:2)

加载文件时尝试此操作

$xml = simplexml_load_file($this->filename,'SimpleXMLElement', LIBXML_NOCDATA);

答案 1 :(得分:0)

试试这个:

var_dump(
    (string)$xml->item->category,
    (string)$xml->item->HEADLINE
);

SimpleXML在运行中构建内容并不值得,因此对象上的print_r()不一定显示有用的信息。

答案 2 :(得分:-1)

尝试施放

[category] => SimpleXMLElement Object
            (
            )

        [HEADLINE] => SimpleXMLElement Object
            (
            )

到字符串,我想你会得到你需要的东西

$item['category']=(string)$item['category'];