1

我想使用 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');
4

1 回答 1

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
于 2012-11-08T02:47:00.920 回答