2014-10-01 63 views
2

这是一个初学者问题(对不起);我使用simplexml_load_string()PHP函数解析一个RSS feed,我的代码看起来是这样的:PHP解析器使用simplexml_load_string()

<?php 

$url = "http://www.zdnet.com/blog/rss.xml"; 
$xml = file_get_contents($url); 
$feed = simplexml_load_string($xml); 

foreach($feed->channel as $channel) { 
    echo "Link : " . $channel->link . "<P>"; 
    echo "Image URL : " . $channel->image->url . "<P>"; 
} 

foreach($feed->channel->item as $item) { 
    echo "<HR><P>"; 
    echo "Link : " . $item->link . "<P>"; 
    echo "Title : " . $item->title . "<P>"; 
    echo "Description : " . $item->description . "<P>"; 
    echo "Date : " . $item->pubDate . "<P>"; 
} 

?> 

这是工作正常,但在XML文件中有一些标签是这个样子:

<media:credit role="author"> 
<![CDATA[ James Kendrick ]]> 
</media:credit> 

<media:text type="html"> 
<![CDATA[ 
<figure class="alignRight"><a href="/i/story/70/00/034218/kindle-iphone-2.jpg" target="_blank">  
<img title="kindle-iphone-2" alt="kindle-iphone-2" src="http://cdn-static.zdnet.com/1.jpg"> 
height="237" width="200"></a><figcaption>(I 
]]> 

<![CDATA[ 
mage: James Kendrick/ ZDNet)</figcaption></figure> <p>Regular readers know I am a tablet guy 
]]> 
</media:text> 

我如何解析这些标签?

感谢

+0

通常你不会在所有的解析CDATA节。只要处理纯文本 – hek2mgl 2014-10-01 11:38:59

+0

您可能会看看http://stackoverflow.com/questions/16547992/xml-cdata-not-returning-properly-with-simplexml-load-string-nor-simplexmleleme – hchr 2014-10-01 11:43:09

回答

0

用于访问与命名空间节点,你可以在这种情况下使用->children()

$url = "http://www.zdnet.com/blog/rss.xml"; 
$feed = simplexml_load_file($url, null, LIBXML_NOCDATA); 

foreach($feed->channel->item as $item) { 
    echo "<HR><P>"; 
    echo "Link : " . $item->link . "<P>"; 
    echo "Title : " . $item->title . "<P>"; 
    echo "Description : " . $item->description . "<P>"; 
    echo "Date : " . $item->pubDate . "<P>"; 

    $media = $item->children('media', 'http://search.yahoo.com/mrss/'); // medias 
    // then just loop the children 
    // foreach($media as $m) {} 
    $s = $item->children('s', 'http://www.zdnet.com/search'); // ss 
}