因此,我尝试在App Service Provider中编写以下函数,但遇到错误:
我的代码是:
public function boot()
{
$homepage = 'https://example.com';
$already_crawled = [];
$crawling = [];
function follow_links($url)
{
global $already_crawled;
global $crawling;
$doc = new \DOMDocument();
$doc->loadHTML(file_get_contents($url));
$linklist = $doc->getElementsByTagName('a');
foreach ($linklist as $link) {
$l = $link->getAttribute("href");
$full_link = 'https://example.com' . $l;
if (!in_array($full_link, $already_crawled)) {
$already_crawled[] = $full_link;
$crawling[] = $full_link;
Log::info($full_link . PHP_EOL);
}
}
array_shift($crawling);
foreach ($crawling as $link) {
follow_links($link);
}
}
follow_links($homepage);
}因此,对于这段代码,我得到了如下错误:
in_array()要求参数%2为数组,但给定的参数为null
我应该怎么做才能运行这个程序而没有问题呢?
发布于 2018-11-21 05:04:59
boot函数中的变量不是global,因此follow_links函数的全局变量是一组完全独立的变量。基本上,在Laravel中的任何地方都不应该有关键字global,永远不应该。
由于您的作用域问题,当您第一次尝试将其提供给is_array时,$already_crawled是未定义的。使用类属性和$this来访问它们。最重要的是,我删除了奇怪的函数中函数结构:
protected $already_crawled;
protected $crawling;
protected $homepage;
public function boot()
{
$this->homepage = 'https://example.com';
$this->already_crawled = [];
$this->crawling = [];
$this->follow_links($this->homepage);
}
protected function follow_links($url)
{
$doc = new \DOMDocument();
$doc->loadHTML(file_get_contents($url));
$linklist = $doc->getElementsByTagName('a');
foreach ($linklist as $link) {
$l = $link->getAttribute("href");
$full_link = 'https://example.com' . $l;
if (!in_array($full_link, $this->already_crawled)) {
$this->already_crawled[] = $full_link;
$this->crawling[] = $full_link;
Log::info($full_link . PHP_EOL);
}
}
array_shift($this->crawling);
foreach ($this->crawling as $link) {
$this->follow_links($link);
}
}附注:几乎可以肯定的是,不希望在您的服务提供商中出现这种情况。它将在你的应用程序为提供服务的每一个页面视图上对进行一个HTTP file_get_contents调用。这将大大降低你的应用程序的速度。
https://stackoverflow.com/questions/53400978
复制相似问题