icetimux
icetimux

Reputation: 255

domcrawler loop and if statement to check if class exists

Hi I'm running into a little problem with DomCrawler. I'm scraping a page and it has a div with a class of .icon3d. I want to go through the page and for every div with that class I will add an "3D" item to an array, and every div without it I will add a "2D" item. Here is the code I have so far.

for ($i=0; $i < 10; $i++) { 
    $divs =  $crawler->filter('div.icon3d');
        if(count($divs)){
            $type[] = '3D';
        }else{
            $type[] = '2D';
        }
    }

Upvotes: 1

Views: 6331

Answers (2)

icetimux
icetimux

Reputation: 255

I figured it out. Here's the code I used. I'm sure there is a cleaner way.

$divs = $crawler->filter('#schedule li a')->each(function($node){
    if ($node->children()->last()->attr('class') == 'icon3d') {
        return '3D';
    }else{
        return '2D';
    }
});

Upvotes: 0

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10136

Check The DomCrawler Component documentation first. filter method returns filtered list of nodes, so by calling ->filter('div.icon3d') returned value will be list of all div elements which have icon3d class.

First you need to find all div elements, loop through them and add either 3D or 2D the to array depending on icon3d css class existance.

$divs = $crawler->filter('div');
foreach ($divs as $node) {
    $type[] = (false !== strpos($node->getAttribute('class'), 'icon3d')) ? '3D' : '2D';
}

UPDATE

$crawler->filter('a')->each(function(Crawler $a) {
    $div = $a->filter('div');
    // Div exists
    if ($div->count()) {

    }
});

To get crawler node class use

$div->getNode(0)->getAttribute('class')

Upvotes: 4

Related Questions