Guzzle/Goutte - 基本抓取 - 将变量传递给请求

Mar*_*ing 0 php goutte guzzle

我目前正在使用一个名为Goutte的简单 php 爬虫。它使用Guzzle来执行 httpGET请求。我能够执行抓取操作。但是,我试图在内部传递/回显一个变量,filter但出现错误Undefined variable: x。变量已定义。将变量传递给过滤器的正确方法是什么?

$client = new Goutte\Client();
$crawler = $client->request('GET', 'http://github.com/');
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form    = $crawler->selectButton('Sign in')->form();
$x       = "hello";
$crawler = $client->submit($form, array('login' => 'xxxxx', 'password' => 'xxxxx'));
$crawler->filter('.flash-error')->each(function ($node) {
    echo $x;
    print $node->text() . "\n";
});
Run Code Online (Sandbox Code Playgroud)

seg*_*ult 5

尝试:

$crawler->filter('.flash-error')->each(function ($node) use (&$x) {
    echo $x;
    print $node->text() . "\n";
});
Run Code Online (Sandbox Code Playgroud)

&如果您不需要在该函数中更改它,则可以将其删除。参考在匿名函数中继承父变量。