2013-03-06 188 views
0

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

回答

1

你應該嘗試

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