0

I was looking through the following stackoverflow question: Getting Dom Elements By Class name and it referenced that I can get class names with this code:

$text = '<html><body><div class="someclass someclass2">sometext</div></body></html>';
$dom = new DomDocument();
$dom->loadHTML($text);
$classname = 'someclass someclass2';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
print "<pre>".print_r($nodes,true)."</pre>";

I also tried changing $classname to just one class:

$classname = 'someclass2';

I'm getting empty results. Any idea why?

Community
  • 1
  • 1
somejkuser
  • 8,656
  • 19
  • 58
  • 122

1 Answers1

0

You'll have to loop trough the results as print_r() will not print the members of a DOMNodeList. Like this:

$text = '<html><body><div class="someclass someclass2">sometext</div></body></html>';
$dom = new DomDocument();
$dom->loadHTML($text);
$classname = 'someclass someclass2';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

// iterate through the result. print_r will not suffer
foreach($nodes as $node) {
    echo $node->nodeValue;
}
hek2mgl
  • 143,113
  • 25
  • 227
  • 253
  • you are welcome. if you need it more often consider to write a function like `dump_xp_results()` – hek2mgl Aug 26 '13 at 22:29