用xpath查询找不到错误,`undefined method DOMDocument`

时间:2013-07-08 22:30:50

标签: php xpath

我的代码的Call to undefined method DOMDocument::xpath()行收到了$level1

          $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>

我正在使用this answer作为xpath查询的参考。

我的查询有什么问题?

1 个答案:

答案 0 :(得分:2)

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');