2010-02-21 65 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');