gpt4 book ai didi

php - 如何检查 URL 是否是 PHP 中的有效 RSS 提要

转载 作者:可可西里 更新时间:2023-11-01 12:30:58 24 4
gpt4 key购买 nike

我有以下代码:

    function parse() {
$content = file_get_contents($this->feed);
$rss = new SimpleXmlElement($content);
$rss_split = array();
$i = 0;
foreach ($rss->channel->item as $item) {
$title = (string) $item->title; // Title
$link = (string) $item->link; // Url Link
$content = $item->children('content', true)->encoded;
preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $content, $image);
$image = substr($image['src'], 0, strpos($image['src'], '"'));
$rss_split[$i]['title'] = $title;
$rss_split[$i]['link'] = $link;
$rss_split[$i]['image'] = $image;
$i++;
}
return $rss_split;
}

此处,$this->feed 包含 RSS 提要的 URL。问题是我不知道如何验证 URL 以确保它是有效的 RSS 提要。

最佳答案

验证它是 XML:

function parse()
{
$content = file_get_contents($this->feed);
try { $rss = new SimpleXmlElement($content); }
catch(Exception $e){ /* the data provided is not valid XML */ return false; }
// rest of your function goes here

一旦您确认它是 XML,您有几个选择:

  1. 您可以检查以确保 isset($rss->channel->item) 存在并且 $rss->channel->item->count() > 0.
  2. 您可以使用 count($rss->xpath(/channel/item)) > 0

我个人会使用 xpath,因为我在阅读代码时发现它更明显一些。


旁注:

是认真的吗?您已经有了 XML 对象。为什么要使用 RegEx?

不要这样做:

preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $content, $image);

当这是一个有效选项时:

$g = $item->xpath('//img'); $g[0]->attributes()->src;

关于php - 如何检查 URL 是否是 PHP 中的有效 RSS 提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com