How can I iterate over DomCrawler results and search for specific elements

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.

Upvotes: 3

Views: 2336

Answers (1)

k.tarkin
k.tarkin

Reputation: 736

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());
        });
    });
});

Upvotes: 5

Related Questions