phpsymfonydomcrawler

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.


Solution

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