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 に答える