not able to retrieve direct child elements using Simple HTML DOM

牧云@^-^@ 提交于 2020-01-06 19:54:11

问题


I have an html table like this

<table>
<tbody>
    <tr>
      <td><table>
          <tbody>
            <tr class="prdLi">
              <td rowspan="2" class="prdNo"><span>310.</span></td>
              <td colspan="2" class="prdDe" rowspan="2"><span>Pepsi</span></td>
            </tr>
            <tr class="prdLi">
              <td class="prdAc"><span> 1.5L</span></td>
              <td><span>&nbsp;</span></td>
            </tr>
          </tbody>
        </table></td>
    </tr>
  </tbody>
</table>

the table is saved as $html

I want to select the child elements of the class .prdLi

I tried like this:

foreach($html->find('tr.prdLi') as $foo){
   echo $foo;

}

the output that i get is like this

<span>310.</span>
<span>Pepsi</span
.
.
.

but what i actually want to get is the code with the parent element td.like this:

<td rowspan="2" class="prdNo"><span>310.</span></td>
<td colspan="2" class="prdDe" rowspan="2"><span>Pepsi</span></td>
.
.
.

please help me


回答1:


Since Simple HTML DOM Parser supports CSS like selectors, you can use 'tr.prdLi td' to specify all td elements which are children of tr with class prdLi. The following should provide what you are looking for:

$htmlstr = <<<EOD
<table>
<tbody>
    <tr>
      <td><table>
          <tbody>
            <tr class="prdLi">
              <td rowspan="2" class="prdNo"><span>310.</span></td>
              <td colspan="2" class="prdDe" rowspan="2"><span>Pepsi</span></td>
            </tr>
            <tr class="prdLi">
              <td class="prdAc"><span> 1.5L</span></td>
              <td><span>&nbsp;</span></td>
            </tr>
          </tbody>
        </table></td>
    </tr>
  </tbody>
</table>
EOD;

$html = str_get_html($htmlstr);
foreach ($html->find('tr.prdLi td') as $foo) {
    echo $foo . "\n";
}

Note that find() is called on the main simple_html_dom-element. In your example, the result was already limited by a previous find().




回答2:


What andy says is correct, but the css for direct child is > *, therefore:

foreach($html->find('tr.prdLi > *') as $foo){
   echo $foo . "\n";
}


来源:https://stackoverflow.com/questions/26338700/not-able-to-retrieve-direct-child-elements-using-simple-html-dom

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