1

I'm looking to find a specific attribute of a specific element in an HTML document using PHP DOMDocument.

Specifically, there is a div with a unique class set, and only a single span inside of it. I need to retrieve the style attribute of that span element.

Example:

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

For this example, with the uniqueClass being the only instance of that class in the document, I would need to retrieve the string:

text-align: center;

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Slyder
  • 11
  • 2
  • See question http://stackoverflow.com/questions/2571232/parse-html-with-phps-html-domdocument/22345590#22345590 – lokeshsk Mar 12 '14 at 08:22

2 Answers2

4

You have to use DOMXPAth class

$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')
Ololo
  • 1,087
  • 9
  • 16
1
$xpath = new DomXPath($doc);
$result = $xpath->evaluate('//div[@class=uniqueClass]/span/@style');
Scharrels
  • 3,055
  • 25
  • 31