0

我只是想知道其他开发人员如何设法从 RSS 提要中的 URL 正确获取/提取网站的博客主要内容中的第一张图片。这是我想到的方式,因为 RSS 提要中没有帖子/博客项目的图像 URL。虽然我一直在看

<img src="http://feeds.feedburner.com/~r/CookingLight/EatingSmart/~4/sIG3nePOu-c" />

但它只有 1px 的图像。这个是否对提要项具有相关价值,或者我可以将其转换为实际图像吗?这是 RSS http://feeds.cookinglight.com/CookingLight/EatingSmart?format=xml

无论如何,这是我使用提要中的 url 提取图像的尝试:

function extact_first_image( $url ) {  
  $content = file_get_contents($url);

  // Narrow the html to get the main div with the blog content only.
  // source: http://stackoverflow.com/questions/15643710/php-get-a-div-from-page-x
  $PreMain = explode('<div id="main-content"', $content);
  $main = explode("</div>" , $PreMain[1] );

  // Regex that finds matches with img tags.
  $output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $main[12], $matches);  

  // Return the img in html format.
  return $matches[0][0];  
}

$url = 'http://www.cookinglight.com/eating-smart/nutrition-101/foods-that-fight-fat'; //Sample URL from the feed.
echo extact_first_image($url);

<div id="main-content"此功能的明显缺点:如果在 html 中找到它,它会正确爆炸。当有另一个 xml 用另一个结构解析时,也会有另一个爆炸。这是非常静态的。

我想它值得一提的是关于加载时间。当我循环遍历提要中的项目时,它会更长。

我希望我把要点说清楚了。随意提出任何可能有助于优化解决方案的想法。

4

1 回答 1

1

图片 url 在 rss 文件中,所以你可以通过解析 xml 来获取它们。每个 <item> 元素都包含一个 <media:group> 元素,该元素包含一个 <media:content> 元素。该项目的图像 url 位于 <media:content> 元素的“url”属性中。这是一些用于将图像 url 提取到数组中的基本代码 (php):

$xml = simplexml_load_file("http://feeds.cookinglight.com/CookingLight/EatingSmart?format=xml");

$imageUrls = array();

foreach($xml->channel->item as $item)
{
    array_push($imageUrls, (string)$item->children('media', true)->group->content->attributes()->url);
}

但请记住,媒体不一定是图像。它可以是视频或音频记录。甚至可能有多个 <media:group>。您可以检查 <media:content> 元素的“type”属性以查看它是什么。

于 2014-08-18T18:07:36.837 回答