【问题标题】:way to call a function as a parameter on another function?如何将一个函数作为另一个函数的参数调用?
【发布时间】:2021-09-07 21:58:19
【问题描述】:

我希望这个函数从网站上抓取链接:

function filter ($url)
{
    $content = file_get_contents($url);
    $dom = new DOMDocument();
    @$dom->loadHTML($content);
    $outcomes = $dom->getElementsByTagName('a');

    foreach ($outcomes as $outcome) {
        $seeds = $outcome->getAttribute('href');
    }
}

$index = "scrap.html";
$fn = filter($index);

我希望这个函数从我从上述函数获取的那些 url 中抓取元数据以进行抓取:

function meta_crawl($site) {
    $get_meta = get_meta_tags($site);
    $meta_list = array();
    $meta_list[] = $get_meta['keywords'];
    $meta_list[] = $get_meta['description'];
    $keywords = explode(',', $meta_list[0]);

    foreach ($keywords as $keyword) {
        $keyword;
        $a[] = $keyword;
    }

    $keywordList = [];
    array_push($keywordList, $a);
    print_r($keywordList);
}

我想从过滤器函数中调用@seed 变量@ 也许它会起作用:

meta_crawl($fn($seeds));

【问题讨论】:

  • filter() 需要返回一些东西。

标签: javascript php function web-crawler


【解决方案1】:

filter() 需要返回一个 URL 数组。

然后循环遍历该数组,调用meta_crawl()

分配给$afor 循环没有意义。它只是将$a 复制为$keywords,因此您可以在其余代码中使用$keywords

在新创建的数组上一次使用array_push() 是没有意义的。只需将变量设为数组的内容即可。我也不确定你为什么需要$keywordList 变量,你可以直接转储$keywords

<?php

$index = "scrap.html";
$fn = filter($index);
foreach ($fn as $url) {
    meta_crawl($url);
}

function filter($url) {
    $content = file_get_contents($url);
    $dom = new DOMDocument();
    @$dom->loadHTML($content);
    $outcomes = $dom->getElementsByTagName('a');
    $seeds = []
    foreach ($outcomes as $outcome) {
        $seeds[] = $outcome->getAttribute('href');
    }
    return $seeds;
}

function meta_crawl($site) {
    $get_meta = get_meta_tags($site);
    $meta_list = array();
    $meta_list[] = $get_meta['keywords'];
    $meta_list[] = $get_meta['description'];
    $keywords = explode(',', $meta_list[0]);

    $keywordList = [$keywords];
    print_r($keywordList);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 2020-03-09
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多