php - 从 RSS 源解析图像
问题描述
这是我现在拥有的代码。我正在尝试获取该站点的图像,但该变量没有返回任何内容,这意味着我已经找了好几个小时了,我无法获取它
$html = "";
$url = "https://www.idownloadblog.com/tag/jailbreak/rss";
$xml = simplexml_load_file($url);
for($i = 0; $i < 1; $i++){
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description;
$pubDate = $xml->channel->item[$i]->pubDate;
$image= $xml->channel->item[$i]->content;
$box1 .= "<a><b>$title</b></a>";
$dbox1 .= "$description";
}
解决方案
查看您提供的 RSS 提要,似乎没有站点图像。因此,如果您想要网站的徽标,您可能必须静态链接它。
如果您想获取帖子的图像,我们可以做到。这就是我要做的。
我创建了一个包来使 xml 解析变得轻而易举。你可以在这里找到它:https ://github.com/mtownsend5512/xml-to-array
然后执行以下操作:
$xml = \Mtownsend\XmlToArray\XmlToArray::convert(file_get_contents('https://www.idownloadblog.com/tag/jailbreak/feed/'));
现在你有一个很好的 php RSS 提要数组。
接下来,我们将创建一个辅助函数来从帖子正文中获取第一张图片。我们将使用它作为帖子的特色图片。
function getPostImage($content)
{
$output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches);
if (empty($matches[1][0])) {
return 'http://yoursite.com/images/fallback-image.jpg';
}
return $matches[1][0];
}
http://yoursite.com/images/fallback-image.jpg
如果帖子中没有图片,您需要替换为您的后备图片的网址。
现在,我们循环浏览这些帖子:
foreach ($xml['channel']['item'] as $post) {
$title = $post['title']);
$link = $post['link'];
$description = $post['description'];
$pubDate = $post['pubDate'];
$image = getPostImage($post["content:encoded"]);
}
推荐阅读
- segmentation-fault - 气流2.0:pip3安装'apache-airflow [amazon]'时出现分段错误(核心转储)
- r - 折叠一个数据框列表并与 R 中的另一个数据框列表组合
- vba - 在 MS Access 中禁用过滤/未过滤和切换过滤器按钮
- jmeter - JMeter 可以在使用 Blazor 框架开发的应用程序上记录请求吗?
- sql - 使用oracle sql中的窗口函数检查分区中是否存在值
- nlp - 如何为 LayoutLM 准备自定义训练数据
- python - 使用 setuptools 的 python 替代包设置
- statistics - 如何在 Grafana 中按月创建平均值直方图?
- c# - 如何读取和查找 txt 文件中的特定信息并将其与字符串统一进行比较
- python - 在 Python Pandas 中读取带有印地语数据的 Excel