可以';找不到xpath查询“undefined method DOMDocument”的错误


Can't find error with xpath query, `undefined method DOMDocument`

我在代码的$level1行得到一个Call to undefined method DOMDocument::xpath()

          $doc = new DOMDocument();
          $doc->strictErrorChecking = FALSE;
          $doc->loadHTML($html);
          $xml = simplexml_import_dom($doc);
          $level1 = $doc->xpath('//*[contains(concat(" ", normalize-space(@class), " "), " category-wrap ")]/h2/a');

这是它正在加载的html(通过file_get_contents()):

<div class="category-wrap">
   <a href='#'>LINK</a>
   <h2><a href="#">Trying to get this....</a></h2>
   <p>A description</p>
</div>

我使用这个答案作为xpath查询的参考。

我的查询出了什么问题?

DOMDocument中没有xpath这样的方法。看见http://php.net/manual/en/class.domdocument.php

您需要初始化DOMXpath的实例才能使用xpath查询

$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);

或者调用您创建的SimpleXMLObject上的方法

$level1 = $xml->xpath('//*[contains(concat(" ", normalize-space(@class), " "), " category-wrap ")]/h2/a');