如何从标签中的XML获取2个CDATA值?
问题描述:
我使用笨的框架,我有一个xml
文件与下面的代码:如何从<content:encoded>标签中的XML获取2个CDATA值?
<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>
这个数据解析?
答
我得到的答案也一样,我所做的是:
<?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");
}
}
?>