如何从<content:encoded>标签中的XML获取2个CDATA值?

时间:2015-12-30 06:56:03

标签: xml codeigniter

我正在使用codeigniter框架,我有一个xml文件,代码如下:

<rss xmlns:content="" xmlns:wfw="" xmlns:dc="" xmlns:atom="" xmlns:sy="" xmlns:slash="" version="2.0">
    <channel>
        <item>
            <title>Title1</title>
            <link>Link</link>
            <pubDate>Date</pubDate>
            <content:encoded>
                <![CDATA[ This is description 1 ]]>
                <![CDATA[ This is description 2 ]]>
            </content:encoded>
        </item>

        <item>
            <title>Title2</title>
            <link>Link2</link>
            <pubDate>Date2</pubDate>
            <content:encoded>
                <![CDATA[ This is description 3 ]]>
                <![CDATA[ This is description 4 ]]>
            </content:encoded>
        </item>
</channel>
</rss>

我试过这个来解析xml

<?php
function test()
{
    $xml = simplexml_load_file('http://localhost/testxml/testxml.xml','SimpleXMLElement',LIBXML_NOCDATA);
    echo "<pre>";
    print_r($xml);
    echo "</pre>";
}
?>

它为我提供了没有 CDATA 的输出,该标签中包含内容:已编码:

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

    [channel] => SimpleXMLElement Object
        (
            [item] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [title] => Title1
                            [link] => Link
                            [pubDate] => Date
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [title] => Title2
                            [link] => Link2
                            [pubDate] => Date2
                        )

                )

        )

)

如何在解析时获取<content:encoded><![CDATA[ This is description 1 ]]><![CDATA[ This is description 2 ]]></content:encoded>这些数据?

1 个答案:

答案 0 :(得分:0)

我也得到了答案,我做的是:

<?php
function getFeed() {
        $feed_url = 'http://localhost/testxml/testxml.xml';
        $feeds = file_get_contents($feed_url);
        $feeds = str_replace("<content:encoded>","<contentEncoded>",$feeds);
        $feeds = str_replace("</content:encoded>","</contentEncoded>",$feeds);
        $rss = simplexml_load_string($feeds);

        foreach($rss->channel->item as $entry) {
            echo ("<a href='$entry->link' title='$entry->title'>" . $entry->title . "</a>");
            echo ("$entry->contentEncoded");
        }
    }
?>