2010-02-21 64 views
1

我正在尋找使用PHP DOMDocument的HTML文檔中的特定元素的特定屬性。PHP DOMDocument,查找特定元素

具體而言,有一個div具有唯一的類集,並且只有一個跨度。我需要檢索該span元素的樣式屬性。

例子:

<div class="uniqueClass"><span style="text-align: center;" /></div> 

在這個例子中,與uniqueClass是在文檔中該類的唯一實例,我需要獲取字符串:

文本對齊:中心;

+0

見問題http://stackoverflow.com/questions/2571232/parse-html-with-phps-html-domdocument/22345590#22345590 – lokeshsk 2014-03-12 08:22:01

回答

4

你必須使用DOMXPAth類

$doc = new DOMDocument; 
// We don't want to bother with white spaces 
$doc->preserveWhiteSpace = false; 

$doc->loadHTML($htmlSource); 

$xpath = new DOMXPath($doc); 

// We starts from the root element 
$query = '//div[@class= uniqueClass]/span'; 

$entries = $xpath->query($query); 

$spanStyle = $entries->current()->getAttribute('style') 
+1

該死的我打字慢,這幾乎是完全相同的解決方案,我要建議:) – Steve 2010-02-21 11:16:30

+0

啊哈,「xpath」。我將對此進行必要的研究。 謝謝! – Slyder 2010-02-21 22:00:30

1
$xpath = new DomXPath($doc); 
$result = $xpath->evaluate('//div[@class=uniqueClass]/span/@style');