获取课堂上的所有元素

时间:2012-11-08 01:41:16

标签: php class dom

我想使用PHP DOM来获取特定类中的所有元素。

我的HTML

<tr>
  <td><ul class="up">
      <li><a href="/updown.html#ud1">Russia</a></li>
      <li><a href="/updown.html#ud2">Pakistan</a></li>
          <li><a href="/updown.html#ud3">Iran</a></li>
    </ul></td>
</tr>

<tr>

  <td valign="top"><ul class="down">
      <li><a href="/updown.html#ud4">Spain</a></li>
      <li><a href="/updown.html#ud5">France</a></li>
    </ul></td>
</tr>

为什么这个PHP不起作用?

$elements = $xpath->query('//ul[@class="up"]'); 
$elements = $elements->getElementsByTagName('li');

1 个答案:

答案 0 :(得分:2)

尝试 -

....

$xpath = new DOMXPath($dom);                     
$nodes = $xpath->query('//ul[@class="up"]'); 

foreach($nodes as $node) {                      

    foreach($node->getElementsByTagName('li') as $li) {

    ....  // li elements of ul with class="up"

    }
}

所以使用以下代码 -

<?php 
$str = '
<table>
<tr>
  <td><ul class="up">
      <li><a href="/updown.html#ud1">Russia</a></li>
      <li><a href="/updown.html#ud2">Pakistan</a></li>
      <li><a href="/updown.html#ud3">Iran</a></li>
    </ul></td>
</tr>

<tr>

  <td valign="top"><ul class="down">
      <li><a href="/updown.html#ud4">Spain</a></li>
      <li><a href="/updown.html#ud5">France</a></li>
    </ul></td>
</tr>
</table>';

$dom = new DOMDocument;

$dom->loadHTML($str);
$xpath = new DOMXPath($dom);                     
$nodes = $xpath->query('//ul[@class="up"]');   // get <ul>'s with class 'up'
foreach($nodes as $node) {                      // loops through each <ul>
    foreach($node->getElementsByTagName('li') as $li) {    // loops through the <li>'s

    echo $li->nodeValue . "<br/>\n";   // echo's the <li> elements

}}

?>

输出是 -

Russia
Pakistan
Iran