【问题标题】:Getting first image from RSS feed (PHP CURL)从 RSS 提要 (PHP CURL) 获取第一张图片
【发布时间】:2013-01-05 02:33:44
【问题描述】:

下面的代码可以使用 PHP CURL 从 RSS 提要中提取数据,但是我似乎无法弄清楚如何从描述变量中获取图像 URL。我只需要第一张图片。

Fatal error: Call to undefined method SimpleXMLElement::description() in      /home/feedolu/public_html/index.php on line 26 

    Function feedMe($feed) {
// Use cURL to fetch text
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, $useragent);
$rss = curl_exec($ch);
curl_close($ch);

// Manipulate string into object
$rss = simplexml_load_string($rss);

$siteTitle = $rss->channel->title;
echo "<h1>".$siteTitle."</h1>";
echo "<hr />";

$cnt = count($rss->channel->item);

for($i=0; $i<$cnt; $i++)
{
    $url = $rss->channel->item[$i]->link;
    $title = $rss->channel->item[$i]->title;
    $desc = $rss->channel->item[$i]->description;
    $image = $rss->channel->item[$i]->description('img', 0);
    echo '<h3><a href="'.$url.'">'.$title.'</a></h3>'.$desc.'';
    echo $image;
}
}

 feedMe("localhost/feed/");

【问题讨论】:

    标签: php curl


    【解决方案1】:

    问题显然与这个链接有关:

    $image = $rss->channel->item[$i]->description('img', 0);
    

    SimpleXML 类的上下文中,description 是一个属性,而不是一个函数。使用xpath() 函数查找所有&lt;img /&gt; 可以快速解决问题。

    因此,根据您的代码,我将如何获得您正在寻找的价值(即使我认为您的实现不是最好的):

    $images = $rss->channel->item[$i]->description->xpath('img');
    if (count($images) > 0) {
        $image = $images['src'];
    }
    

    【讨论】:

    • 我以前没想过。我需要从中提取图像的标签是内容。这当然是内容:编码。由于“:”,这不起作用。 for($i=0; $ichannel->item[$i]->link; $title = $rss->channel->item[$i]->title; $desc = $rss->channel->item[$i]->description; $content = $rss->channel->item[$i]->content:encoded; $images = $rss->channel->item[$i]->content->xpath('img'); if (count($images) > 0) { $image = $images['src']; } }
    • 好的,我现在必须接近内容:encode thingie for($i=0; $ichannel->item[ $i]->链接; $title = $rss->channel->item[$i]->title; $desc = $rss->channel->item[$i]->description; $content = $rss->channel->item[$i]->xpath('content:encoded'); $images = $rss->channel->item[$i]->content->xpath('img'); if (count($images) > 0) { $image = $images['src']; } echo '

      '.$title.'

      '.$desc.'';回声$图像;回声$内容; } }
    【解决方案2】:

    此页面上的解决方案对我有用:-

    How to get first image from a tumlbr rss feed in PHP

    $image = '';
    if (preg_match('/src="(.*?)"/', $rss->channel->item[$i]->description, $matches)) {
        $image = $matches[1];
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多