MaryCoding MaryCoding - 1 year ago 69
PHP Question

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

requests. I am able to perform scrape actions. However, I am trying to pass/echo a variable inside
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', '');
$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";

Answer Source


$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.