【问题标题】:How to collect all info from a rss feed using PHP [duplicate]如何使用 PHP 从 rss 提要中收集所有信息 [重复]
【发布时间】:2014-11-01 09:19:03
【问题描述】:

我需要使用 PHP 显示来自 rss 提要的此类信息

标题、链接/网址、描述和图片

我已经在下面完成了这段代码,但我无法从提要中获取图像

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

<?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.'';
    }
}


?>

【问题讨论】:

    标签: php xml rss simplexml


    【解决方案1】:

    您已经在使用-&gt;attributes() 的正确轨道上,对于那些有命名空间的人,只需使用-&gt;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

    【讨论】:

    • 谢谢你的帮助,你的例子对我有用,现在我要修改我的脚本。谢谢
    • @user3040570 很高兴这有帮助
    • 你能帮我找出今天添加到 rss 的帖子吗?
    • @user3040570 只需在$pubDate 中使用strtotime(),然后将其与今天的日期进行比较,将其放在if 条件中,这应该相当简单。像这样:if(date('Y-m-d', strtotime($pubDate)) == date('Y-m=d')) {
    • 是的,我也在这样做 -:) 非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2015-05-10
    相关资源
    最近更新 更多