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:
<table>
<tr>
<th class="h1">ONE</td>
<th class="h2">TWO</td>
<th class="h3">THREE</td>
</tr>
<tr>
<td class="one">Apple</td>
<td class="two">Orange</td>
<td class="null">N/A</td>
</tr>
<tr>
<td class="one">Apple</td>
<td class="null">N/A</td>
<td class="three">Banana</td>
</tr>
</table>
The table looks something like this , so i am traversing the table via tr
foreach ($demo->find("tr") as $val)
{
if(is_object($val->find('td.null', 0))
{
echo "FOUND";
}
}
But the above foreach loop returns "FOUND" if td.null exist.
But I need to find if 2nd element td class is null i need to return as TWO, If third td element class is null i need to return as Three
I hope so that you understand that what i am asking for , so please help me of how to find the nth element class is null
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.
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.