如何使用 domdocument php 只调用一次 UL 类


How to call UL class only once using domdocument php

我正在使用PHP Domdocument来加载我的html。在我的HTML中,我有两次class="smalllist"。但是,我需要加载第一类元素。

现在,我的PHP代码是

    $d = new DOMDocument();
    $d->validateOnParse = true;
    @$d->loadHTML($html);
    $xpath = new DOMXPath($d);
    $table = $xpath->query('//ul[@class="smalllist"]');
    foreach ($table as $row) {
       echo $row->getElementsByTagName('a')->item(0)->nodeValue."-";
       echo $row->getElementsByTagName('a')->item(1)->nodeValue."'n";
    }

这将加载两个类。但是,我只需要加载一个具有该名称的类。请帮我解决这个问题。提前谢谢。

DOMXPath返回一个具有item()方法的DOMNodeList。 看看这是否有效

$table->item(0)->getElementsByTagName('a')->item(0)->nodeValue

已编辑(未经测试(:

foreach($table->item(0)->getElementsByTagName('a') as $anchor){
  echo $anchor->nodeValue . "'n";
}
您可以在

foreach循环中放置一个break,以便仅从第一个类读取。或者,您可以执行foreach ($table->item(0) as $row) {...

法典:

$count = 0;
foreach($table->item(0)->getElementsByTagName('a') as $anchor){
   echo $anchor->nodeValue . "'n";
   if( ++$count > 2 ) {
      break;
   }
}

另一种方式而不是使用break(不止一种给猫剥皮的方法(:

$anchors = $table->item(0)->getElementsByTagName('a');
for($i = 0; $i < 2; $i++){
  echo $anchor->item($i)->nodeValue . "'n";
}
这是我

的最终代码:

        $d = new DOMDocument();
        $d->validateOnParse = true;
        @$d->loadHTML($html);
        $xpath = new DOMXPath($d);
        $table = $xpath->query('//ul[@class="smalllist"]');
        $count = 0;
        foreach($table->item(0)->getElementsByTagName('a') as $anchor){
           $data[$k][$arr1[$count]] = $anchor->nodeValue;
           if( ++$count > 1 ) {
              break;
           }
        }

工作正常。