phpguzzlegoutte

Guzzle/Goutte - Basic scrape - passing variable to request


I am currently using a simple php crawler called Goutte. It uses Guzzle to perform the http GET requests. I am able to perform scrape actions. However, I am trying to pass/echo a variable inside filter but get the error Undefined variable: x. The variable is defined. What would be the correct way to pass a variable to filter?

$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";
});

Solution

  • Try:

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

    You can remove & if you don't need to alter it in that function. For reference to inheriting parent variables inside anonymous functions.