Symfony2 DomCrawler each Loop will not add a new StdClass object to an 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 is var_dump($results)always a completely empty object:

object(stdClass)[176]

The URL is correct and the filter is correct, the class works, but if I use $nodeand get text from HTML, it works in a loop, but the data is not stored inside it in the $resultsObject.

As in the example above, the text 'hello' in the class $itemis not even present in the final $resultsobject.

+4
source share
2 answers

You need to allow the anonymous function to access the local variable, by the way, I don’t see what you are using $nodeinside your closure

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

    $results->data[] = $item;
}
+3

:

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

- Symfony.

+7

Source: https://habr.com/ru/post/1542573/


All Articles