You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何将函数作为参数调用 实现爬取链接后提取元数据

问题解决方法

现有代码核心问题

  • filter函数无返回值:当前filter函数执行后没有return任何结果,$fn = filter($index)实际拿到的是null,无法作为函数调用
  • 链接存储逻辑错误:循环内每次给$seeds赋值都会覆盖上一条结果,没有把所有爬取到的href存入集合,且$seeds是函数内部局部变量,外部无法直接访问
  • 调用逻辑不符合语法:meta_crawl($fn($seeds))中$fn为null、$seeds在全局作用域不存在,必然报错

基础实现方案(爬取链接后批量提取元数据)

首先修正filter函数,让它返回所有爬取到的链接:

function filter ($url)
{
    $content = file_get_contents($url);
    $dom = new DOMDocument();
    @$dom->loadHTML($content);
    $outcomes = $dom->getElementsByTagName('a');
    // 初始化数组存储所有链接
    $seeds = [];
    foreach ($outcomes as $outcome) {
        $href = $outcome->getAttribute('href');
        // 可在这里增加非空判断、无效链接过滤逻辑
        if (!empty($href)) {
            $seeds[] = $href;
        }
    }
    // 返回链接数组
    return $seeds;
}

调用逻辑:

$index = "scrap.html";
// 拿到所有爬取到的链接
$seedList = filter($index);
// 遍历每个链接调用元数据提取函数
foreach ($seedList as $site) {
    meta_crawl($site);
}

函数作为参数传入的实现方案(对应核心需求)

如果需要把元数据提取函数作为参数传入爬取函数,实现爬取完自动执行对应逻辑,可以修改filter函数支持传入回调参数:

// 增加$callback参数,支持传入处理链接的函数
function filter ($url, callable $callback = null)
{
    $content = file_get_contents($url);
    $dom = new DOMDocument();
    @$dom->loadHTML($content);
    $outcomes = $dom->getElementsByTagName('a');
    $seeds = [];
    foreach ($outcomes as $outcome) {
        $href = $outcome->getAttribute('href');
        if (!empty($href)) {
            $seeds[] = $href;
            // 如果传入了回调函数,直接用当前链接执行回调
            if (!is_null($callback)) {
                $callback($href);
            }
        }
    }
    return $seeds;
}

调用的时候直接把meta_crawl作为参数传入即可:

$index = "scrap.html";
// 爬取的同时自动对每个链接执行元数据提取
filter($index, 'meta_crawl');

额外提示:你当前的meta_crawl函数中$a变量没有初始化,建议在函数开头加$a = [];避免PHP报错。

内容的提问来源于stack exchange,提问作者Abdul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:39:04