使用XPath检索元素

问题描述:

HTML部分:使用XPath检索元素

<div class="abc"> 
    <div style="text-align:left; itemscopr itemtype="xyz"> 
     <h1 itemtype="mno"> I want this text </h1> 
    </div> 
</div> 

我使用

$text = $xpath->query('//div[class="abc"]/div/h1] 

,但我越来越没有价值。请帮助我,因为我是新手。

+0

也许你错过了文本()[1]在结束 – mlwacosmos 2013-03-06 16:47:29

你应该尝试

//div[@class="abc"]/div/h1 

所不同的是在@标志class之前,因为the attribute axis is accessed this way。当您省略@标志时,它会查找节点名称(标签名称)。

这会返回整个h1节点(或者说,包含所有匹配的h1节点的节点集)。

如果你只是想从元素中的文本,请尝试evaluate函数:

$text = $xpath->evaluate("//div[@class='abc']/div/h1/text()") 
+0

我都试过,但我没有得到一个空的结果。我如何从中检索价值。我也试过在最后使用text(),但没有运气。有没有其他的方式可能使用正则表达式来检索或使用XPath是更好的选择? – user2140852 2013-03-06 16:55:39

+0

@ user2140852我编辑我的答案以考虑。现在好多了? – 2013-03-06 17:00:38

+0

另外,请确保您将'query'的结果作为节点集处理。因此,您应该遍历所有元素 - 请参阅示例[here](http://www.php.net/manual/en/class.domxpath.php)。 – 2013-03-06 17:03:15