Symfony Dom Crawler Array Push Each

56 views Asked by At

I am stumped by this one. I'm using Symfony's Dom crawler to filter some elements before extracting node data to push into array that can be converted to json. Yet the code below throws up a "Uncaught TypeError: array_push(): Argument #1 ($array) must be of type array" error.

    if($query == 'begin') {
      $persons = $crawler->filter('#content > table > tr > td > a');
        $trial = [];
            $persons->each(function (Crawler $node) {

                $holder['name'] = $node->text();
                $holder['url'] = $node->attr('href');
                print_r($holder['name']);
                // Correct value printed
                print_r($holder['url']);
                // Correct value printed
;               array_push($trial, $holder);

    });    
    var_dump($trial);

print_r shows the expected key-value yet the $trail array is null.

Yet the correct values are given when I try:

$persons->each(function (Crawler $node) {
                    echo "<div class='col col-lg-3'>
                            <a href='{$node->attr('href')}'>{$node->text()}</a>   
                          </div>";
                }); 
2

There are 2 answers

0
monkeytrick On BEST ANSWER

Seems the issue was with returning the values on the foreach loop. Managed to solve it with the code below:

if($query == 'begin') {
    
  $trial = [];

  $persons = $crawler->filter('#content > table > tr > td > a');

  $trial = $persons->each(function (Crawler $node)  {

    $holder['name'] = $node->text();
    $holder['url'] = $node->attr('href');

    return $holder;

}); 

Hat-tip to this thread - https://github.com/FriendsOfPHP/Goutte/issues/266

0
Mmx On

Your problem are in variable scope. Function each have own local scope. Variable $trial is in local scope of upper function. There are two different local scopes, that is a reason why you can not "see" this variable.

      $persons = $crawler->filter('#content > table > tr > td > a');
      $holders = $persons->each(function (Crawler $node) {

                $holder['name'] = $node->text();
                $holder['url']  = $node->attr('href');
                
                return $result[$holder['name']] = $holder['url'];
       });