2013-08-26 56 views
0

我一直在尋找通過以下計算器問題:Getting Dom Elements By Class name,它引用了我能得到的類名稱與此代碼:DOM的XPath選擇不斂類

$text = '<html><body><div class="someclass someclass2">sometext</div></body></html>'; 
$dom = new DomDocument(); 
$dom->loadHTML($text); 
$classname = 'someclass someclass2'; 
$finder = new DomXPath($dom); 
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]"); 
print "<pre>".print_r($nodes,true)."</pre>"; 

我也試圖改變$classname只是一個類:

$classname = 'someclass2'; 

我得到空的結果。任何想法爲什麼?

+0

這適用於我看http://codepad.org/1O17uu5x http://codepad.org/Dk2f7o4Q – Musa

回答

0

由於print_r()將不會打印DOMNodeList的成員,因此您必須循環搜索結果。像這樣:

$text = '<html><body><div class="someclass someclass2">sometext</div></body></html>'; 
$dom = new DomDocument(); 
$dom->loadHTML($text); 
$classname = 'someclass someclass2'; 
$finder = new DomXPath($dom); 
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]"); 

// iterate through the result. print_r will not suffer 
foreach($nodes as $node) { 
    echo $node->nodeValue; 
} 
+0

歡迎您。如果你需要的話,更經常考慮編寫一個像'dump_xp_results()'這樣的函數 – hek2mgl