2011-02-25 45 views
5

在DOMDocument類中,有一些方法可以通過id和標記名稱(getElementById & getElementsByTagName)獲取元素,但不能通過類獲取元素。有沒有辦法做到這一點?使用DOMDocument從HTML文檔中提取類

作爲一個例子,我將如何從以下標記中選擇div?

<html> 
... 
<body> 
... 
<div class="foo"> 
... 
</div> 
... 
</body> 
</html> 
+0

可能重複[DOM文檔需要搜索具有屬性class =「something」]的元素(http://stackoverflow.com/questions/3443701/domdocument-need-to-search-for-an-element-that-has-attribute-class-something) – mario

回答

11

簡單的答案是使用XPath:

$dom = new DomDocument(); 
$dom->loadHtml($html); 
$xpath = new DomXpath($dom); 
$div = $xpath->query('//*[@class="foo"]')->item(0); 

但是,這不會接受的空間。因此,通過空格分隔類選擇,使用此查詢:

//*[contains(concat(' ', normalize-space(@class), ' '), ' class ') 
+0

很好的答案。打敗我吧。 –

+0

查看我的替代使用表[contains(@class,'$ classname')] – RafaSashi

2
$html = '<html><body><div class="foo">Test</div><div class="foo">ABC</div><div class="foo">Exit</div><div class="bar"></div></body></html>'; 

$dom = new DOMDocument(); 
@$dom->loadHtml($html); 

$xpath = new DOMXPath($dom); 

$allClass = $xpath->query("//@class"); 
$allClassBar = $xpath->query("//*[@class='bar']"); 

echo "There are " . $allClass->length . " with a class attribute<br>"; 

echo "There are " . $allClassBar->length . " with a class attribute of 'bar'<br>"; 
0

除了ircmaxell的回答,如果你需要用空格分隔類選擇:中

$dom = new DomDocument(); 
$dom->loadHtml($html); 
$xpath = new DomXpath($dom); 
$classname='foo'; 
$div = $xpath->query("//table[contains(@class, '$classname')]")->item(0);