xpath查询不正确

时间:2016-06-06 20:53:13

标签: php xpath

我试图从这个html汇总俱乐部电话号码。

这是我的HTML:

<div id="content">
  <div class="container">
    <div class="padded">
       <ul class="state-list">
       <ul class="state-city-list">
          <li class="jumper">
        <div class="clubinfo">
            <div class="clubaddress">123 West Palm Blvd</div>
            <div class="clubphone">5555551123</div>
        </div>
          </li>
       </ul>                    
       <ul class="state-city-list">
          <li class="jumper">
        <div class="clubinfo">
            <div class="clubaddress">456 West Palm Blvd</div>
            <div class="clubphone">5555555456</div>
        </div>
          </li>
       </ul>
       <ul class="state-city-list">
          <li class="jumper">
        <div class="clubinfo">
            <div class="clubaddress">789 West Palm Blvd</div>
            <div class="clubphone">5555555789</div>
        </div>
          </li>
       </ul>
       <ul class="state-city-list">
          <li class="jumper">
        <div class="clubinfo">
            <div class="clubaddress">213 West Palm Blvd</div>
            <div class="clubphone">5555555213</div>
        </div>
          </li>
       </ul>
       </ul>
    </div>
  </div>
</div>

这是我的PHP代码:

    $htmlfile='phonecontents';
    $xml=new DOMDocument();
    $xml->preserveWhiteSpace=false;
    $xml->loadHTMLFile($htmlfile);
    $xpath = new DOMXpath($xml);
    //$elm = $xpath->query('/div[@id="content"]/div[@class="container"]/div[@class="padded"]/ul[@class="state-list"]/li[@class="jumper"]/div[@class="clubinfo"]/div[@class="clubphone"]');
    $elm = $xpath->query('/div[@id="content"]/div[@class="clubinfo"]/div[@class="clubphone"]');
    if(!is_null($elm)){
      var_dump($elm);
      foreach($elm as $el){
        echo $el->nodeValue."\n";
      }
    } else {
      echo "NO DATA FOUND \n";
    }

我不太确定,因为我是xpath的新手,但我无法正确获取数据。如果你看看PHP代码,你可以看到我尝试了两个不同的查询似乎都没有。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

$elm = $xpath->query('//div[@id="content"]//div[@class="clubinfo"]/div[@class="clubphone"]');

使用一个斜杠表示&#34;直接使用&#34;,使用两个斜杠表示&#34;&#34;的任何后代。