2010-05-17 48 views
0

昨天晚上的類似問題,我無法編輯源HTML,我試圖解析網站上的大量數據來對產品進行價格/比較。大多數情況下,它正在工作,但我現在正在努力讓它更高效,更快速,更輕鬆地閱讀我的意大利麪代碼。PHP Xpath,幫助選擇一個非常特定的節點

我有以下測試代碼;我想要做的只是返回內容的屬性(例如thisiswhatiwant)if productType的nodeValue被存儲,沒有別的。

<div id="productListing"> 

<div class="productDetail"> 
    <span class="productType">Stocked</span>: <span class="productStock"><span class='productContent' content='thisiswhatiwant'></span></span> 
</div> 

<div class="productDetail"> 
    <span class="productType">Non-stocked</span>: <span class="productStock"><span class='productContent' content='xyz'></span></span> 
</div> 

… 

<div class="productDetail"> 
    <span class="productType">Non-stocked</span>: <span class="productStock"><span class='productContent' content='123'></span></span> 
</div> 

</div> 

這是XPath查詢我有這麼遠,但我是丟失在我的大腦至關重要的東西或東西只是沒有點擊進入齒輪呢。

//div[@id="productListing"]/div[@class="productDetail"]/span[@class="productStock"]/preceding-sibling::span[text()="Stocked"] 

基本上,我想從上面的測試代碼的輸出是:

<? 
echo "Output: " . $dom->getAttribute('content'); 
?> 

Output: thisiswhatiwant 

任何人有什麼想法?

回答

2

Assumig即$dom是從給定的XML字符串創建DOMDocument對象:

$xpath = new DOMXPath($dom); 
$q = '//span[@class="productType" and text()="Stocked"]/ancestor::*[@class="productDetail"]/span[@class="productStock"]/span[@class="productContent"]'; 
$res = $xpath->query($q); 
foreach($res as $node) { 
    echo $node->getAttribute('content') . PHP_EOL; 
} 
+0

這做到了!謝謝。 – 2010-05-17 12:23:51

相關問題