如何使用PHP从rss feed收集所有信息

时间:2014-11-01 09:19:03

标签: php xml rss simplexml

我需要使用PHP

从rss Feed中显示此类信息

标题,链接/网址,说明和图片

我已经在下面完成了此代码,但我无法从Feed中获取图像

我查了很多网站,但仍然无法解决这个问题

<?php 

$ch = curl_init("http://economico.sapo.pt/rss/ultimas");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);

$data = curl_exec($ch);
curl_close($ch);

$doc = new SimpleXmlElement($data);
//print_r($doc);

if(isset($doc->channel))
{
    parseRSS($doc);
}
if(isset($doc->entry))
{
    parseAtom($doc);
}

function parseRSS($xml)
{


  // echo "<strong>".$xml->channel->title."</strong>";
    $cnt = count($xml->channel->item);
    for($i=0; $i<$cnt; $i++)
    {
    $postdate = $xml->channel->item[$i]->pubDate;
    //pubDate



    $url    = $xml->channel->item[$i]->link;
    $title  = $xml->channel->item[$i]->title;
    $desc = $xml->channel->item[$i]->description;

    echo $postdate."<br/>".'<a href="'.$url.'">'.$title.'</a><br/>'.$desc.'<br/>';

    }
}

function parseAtom($xml)
{
    echo "<strong>".$xml->author->name."</strong>";
    $cnt = count($xml->entry);
    for($i=0; $i<$cnt; $i++)
    {
    $urlAtt = $xml->entry->link[$i]->attributes();
    $url    = $urlAtt['href'];
    $title  = $xml->entry->title;
    $desc   = strip_tags($xml->entry->content);

    echo '<a href="'.$url.'">'.$title.'</a>'.$desc.'';
    }
}


?>

1 个答案:

答案 0 :(得分:1)

使用->attributes(),您已经走上了正确的轨道,关于名称空间的问题,请使用->children()。简单的例子:

$url = 'http://economico.sapo.pt/rss/ultimas';
$rss = simplexml_load_file($url, null, LIBXML_NOCDATA);

foreach($rss->channel->item as $item) {
    $title = (string) $item->title;
    $link = (string) $item->link;
    $description = (string) $item->description;
    $pubDate = (string) $item->pubDate;

    $media_image_url = '';
    $media_title = '';
    $media = $item->children('media', 'http://search.yahoo.com/mrss/');
    if(isset($media->content)) {
        $media_image_url = (string) $media->content->attributes()->url;
        $media_title = (string) $media->content->title;
    }

    echo "
        Title: $title <br/> 
        Link: $link <br/> 
        Description: $description <br/> 
        Pub Date: $pubDate <br/>
        Image URL: $media_image_url <br/>
        Media Title: $media_title <br/>
        <hr/>
    ";
}

Sample Output