Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 DomCrawler each Loop, will not add new StdClass object to object outside the loop

    use Goutte\Client;

    $results = new StdClass;

    $client = new Client();
    $crawler = $client->request('GET', $url);
    $crawler->filter('.div')->each(function ($node) 
    {
        $item = new StdClass;
        $item->test = 'hello';

        $results->data[] = $item;
    });

    var_dump($results);

The output of var_dump($results) is always a totally empty object:

object(stdClass)[176]

The URL is correct and the filter is correct, the class is working, but if I make use of $node and pull text form the HTML it works within the loop, but the data is not saved within it to the $results Object.

As in the example above, the text 'hello' in the $item class is not even present in the final $results object.

like image 581
Nicekiwi Avatar asked Dec 26 '22 08:12

Nicekiwi


2 Answers

You may try this:

$client = new Client();
$crawler = $client->request('GET', $url);
$results = $crawler->filter('.div')->each(function (Crawler $node, $i) {
    return $node->text();
});
var_dump($results);

Check the reference on Symfony website.

like image 130
The Alpha Avatar answered May 02 '23 13:05

The Alpha


You need to allow the anonymous function to access local variable, btw I don't see that you are using $node inside your closure

function ($node) use ($results)
{
    $item = new StdClass;
    $item->test = 'hello';

    $results->data[] = $item;
}
like image 39
b.b3rn4rd Avatar answered May 02 '23 15:05

b.b3rn4rd