PHP:Simple Dom Parser Find Nth Element Class Exist

余生长醉 提交于 2020-01-05 10:07:30

问题


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


回答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.




回答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.



来源:https://stackoverflow.com/questions/29426510/phpsimple-dom-parser-find-nth-element-class-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!