Laravel中使用willvincent feed reader无法获取RSS订阅源缩略图求助
解决WillVincent Feed Reader无法获取RSS缩略图的问题
我之前也碰到过这个坑,get_thumbnail() 方法只认标准的 <media:thumbnail> 标签,而你目标的CBN新闻RSS源大概率没采用这个标签格式,所以才会一直返回null。咱们可以按下面的思路来解决:
1. 先搞清楚RSS源的图片存储方式
先访问你要解析的RSS地址 http://www.cbn.com/cbnnews/us/feed/,查看源码确认图片的嵌入形式:
- 不少新闻源会用
<enclosure>标签来存放图片链接 - 还有些会把图片直接内嵌在
description或content的HTML内容里
2. 针对性修改代码
方案一:尝试获取Enclosure标签的图片
如果RSS源用了<enclosure>标签,直接用SimplePie的内置方法就能拿到:
Route::get('feed', function(Request $request) { $f = FeedsFacade::make('http://www.cbn.com/cbnnews/us/feed/'); $results = []; foreach($f->get_items(0, $f->get_item_quantity()) as $item) { $i['title'] = $item->get_title(); // 优先尝试官方方法 $thumbnail = $item->get_thumbnail(); // 如果thumbnail为空,尝试获取enclosure的链接 if(!$thumbnail && $item->get_enclosure()){ $thumbnail = $item->get_enclosure()->get_link(); } $i['thumbnail'] = $thumbnail; $i['description'] = $item->get_description(); $i['content'] = $item->get_content(); $i['link'] = $item->get_link(); $i['date'] = $item->get_date(); $results['items'][] = $i; } dd($results); })->name('feed');
方案二:从描述/内容的HTML中提取图片链接
如果图片是放在<img>标签里内嵌在文本中的,就用正则表达式提取:
Route::get('feed', function(Request $request) { $f = FeedsFacade::make('http://www.cbn.com/cbnnews/us/feed/'); $results = []; foreach($f->get_items(0, $f->get_item_quantity()) as $item) { $i['title'] = $item->get_title(); $thumbnail = $item->get_thumbnail(); // 先从description里提取img的src if(!$thumbnail){ preg_match('/<img.*?src="(.*?)"/i', $item->get_description(), $matches); if(isset($matches[1])){ $thumbnail = $matches[1]; } else { // 还可以尝试从正文content里提取 preg_match('/<img.*?src="(.*?)"/i', $item->get_content(), $contentMatches); $thumbnail = $contentMatches[1] ?? null; } } $i['thumbnail'] = $thumbnail; $i['description'] = $item->get_description(); $i['content'] = $item->get_content(); $i['link'] = $item->get_link(); $i['date'] = $item->get_date(); $results['items'][] = $i; } dd($results); })->name('feed');
补充说明
WillVincent的Feed Reader底层依赖SimplePie,你也可以直接调用SimplePie的原生方法,去检查更多自定义的媒体标签,灵活度会更高。
内容的提问来源于stack exchange,提问作者Waleed
相关产品推荐
相关产品推荐

