我只是想知道其他开发人员如何设法从 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 用另一个结构解析时,也会有另一个爆炸。这是非常静态的。
我想它值得一提的是关于加载时间。当我循环遍历提要中的项目时,它会更长。
我希望我把要点说清楚了。随意提出任何可能有助于优化解决方案的想法。