首页 > 解决方案 > 从 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"; 



}

标签: phpxmlrss

解决方案


查看您提供的 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"]);
}

推荐阅读