2012-07-31 230 views
2

我在某些html中加載了這個PHP代碼。與xpath混淆

$dom = new DOMDocument(); 
$dom->loadHTML($somehtml); 

$xpath = new DOMXPath($dom); 
$divContent = $xpath->query('//table[class="defURLP"]'); 

echo $divContent; 

我太糊塗理解相當有什麼需要去這裏的,但是我的願望就它能夠填充變量$ divContent有表的HTML內容與類名defURLP

它目前只是回到

object(DOMNodeList)#3 (0) { } 
+0

什麼是您的XML是什麼樣子? – 2012-07-31 16:36:03

回答

1

您需要檢索來自DOMNodeList之後的第一項由您的XPath查詢返回,因爲可能有不止一個在列表中。

// Queries for tables having class defURLP 
$tables = $xpath->query('//table[class="defURLP"]'); 
// Reference the first one in $divContent 
$divContent = $tables->item(0); 
// Output its nodeValue 
echo $divContent->nodeValue; 

或者遍歷節點列表與foreach

$tables = $xpath->query('//table[class="defURLP"]'); 
// Iterate over the whole node list in $tables (if it is multiple nodes) 
foreach ($tables as $t) { 
    echo $t->nodeValue; 
}