Search code examples
symfonydomcrawler

DOM Crawler and The current node list is empty - how to get list


I need help with DOM Crawler in Symfony 3.2. Here is my code:

$html = file_get_contents('http://www.wakacje.pl/wczasy/peru/');
$crawler = new Crawler($html);

$crawler = $crawler->filter('#gridWithPagination > div > div')->each(function (Crawler $node) {
    return $node->filter('div.desc > a');
});

foreach ($crawler as $item) {
    var_dump($item->attr('href'));
}

As you can see, I want to get the URI parameter from all occurrences on the list, but this code is returning only the first instance, and also an error:

The current node list is empty

What I've missed? Thanks in advance for help.


Solution

  • Not sure why you needed to filter twice, but a more straightforward CSS selector seems to work for me:

    use Symfony\Component\DomCrawler\Crawler;
    
    $html = file_get_contents('http://www.wakacje.pl/wczasy/peru/');
    $crawler = new Crawler($html);
    
    $nodes = $crawler->filter('div#gridWithPagination div.desc a');
    
    $nodes->each(function ($item) {
        echo $item->attr('href').'<br>';
    });