Skip to content Skip to sidebar Skip to footer

PHP:Simple Dom Parser Find Nth Element Class Exist

I am using the PHP Simple DOM Parser for parsing the HTML Page, Now i am lacking in particular point of how to find the nth element class should be a particular class For Example:

Solution 1:

First, what I would do is also iterate each td's thru foreach. So that you'll be able to get which index number key it falls into. (Note that of course its indexing is zero based so it actually starts at 0).

Then inside the inner loop, just check if the class is null, then map it in the corresponding word 1 = one, 2 = two, etc...

Rough example:

$map = array(1 => 'one', 2 => 'two', 3 => 'three');
foreach ($demo->find('tr') as $tr) { // loop each table row
    // then loop each td
    foreach($tr->find('td') as $i => $td) { // indexing starts at zero
        if($td->class == 'null') { // if its class is null
            echo $map[$i+1]; // map it to its corresponding word equivalent
        }
    }
}

So in this case, this would output three and then two. Inside the second table row, the null lands on the third, inside the third row it lands into the second.


Solution 2:

It's a pain to do things like that with simple html dom, if you switch to this one you will be able to do things like:

foreach($demo->find("td.null") as $td){
  echo $td->index;
}

as well as lots of other jquery-style things that you would expect in a modern parsing lib.


Post a Comment for "PHP:Simple Dom Parser Find Nth Element Class Exist"