dpzbh1779 2015-04-03 05:06
浏览 33
已采纳

PHP:简单的Dom Parser查找第N个元素类存在

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

  • 写回答

2条回答 默认 最新

  • douzhen5158 2015-04-03 05:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端