2

Consider a webpage with multiple divs with class day. I have a list of those divs thanks to DOMCrawler:

$crawler = new Crawler($html);
$days = $crawler->filter('.day');

Those day divs contain an array, and I need to iterate over each row, and then each cell. In theory, I would want to do the following:

foreach($days as $day) {
    $rows = $day->filter('tr');
    foreach($rows as $row) {
        $cells = $row->filter('td');
        foreach($cells as $cell) {
            echo ($cell->textContent);
        }
    }
}

But I can't find a way to that correctly.

Louis 'LYRO' Dupont
  • 1,052
  • 4
  • 15
  • 35
  • 1
    When iterating over results you don't get a `Crawler` but a `Node`, you have to reinstantiate a new crawler in each one to use crawler functions. – msg Sep 29 '20 at 12:22

1 Answers1

4

If you don't need those nested loops:

$crawler = new Crawler($html);
$cells = $crawler->filter('.day td');
$cells->each(function (Crawler $cell) {
    dump($cell->text());
});
    

with nested loops like in your example

$crawler = new Crawler($html);
$days = $crawler->filter('.day');
$days->each(function (Crawler $day) {
    $rows = $day->filter('tr');
    $rows->each(function (Crawler $row) {
        $cells = $row->filter('td');
        $cells->each(function (Crawler $cell) {
            dump($cell->text());
        });
    });
});
k.tarkin
  • 726
  • 3
  • 9