2011-02-25 18 views
5

DOMDocumentクラスには、idおよびタグ名(getElementById & getElementsByTagName)で要素を取得するメソッドがありますが、クラスでは使用できません。これを行う方法はありますか?DOMDocumentを使用してクラスごとにHTMLドキュメントから抽出

例として、次のマークアップからdivを選択するにはどうすればよいですか?

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

[DOMDocumentオブジェクトの可能な複製を行う必要があり属性クラス= "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); 

しかし、それはスペースを受け付けません。だから、スペースで区切られたクラスで選択し、このクエリを使用する:あなたがスペースで区切られたクラスで選択する必要がある場合に答えるのをircmaxellに加えて

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

を:

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