tags:

views:

369

answers:

1

Hi guys,

Like I said in the title, I was wondering whether it would be possible and how, to recursively parse an XML document and return all the nodes that have a given argument.

What I'm actually trying to do is to load and XHTML document and return all the nodes (P nodes, DIV nodes, etc.) that have a class equal to a previously defined value.

Thank you in advance for your support, Constantin TOVISI

+3  A: 

Use xpath to lookup the nodes, then just loop over:

$xml = new SimpleXMLElement($string);
$nodes = $xml->xpath("//*[@class='myclass']");

foreach ($nodes as $node) {
    // ...
}

(Not actually tested that, but it should be right.)

Jack Sleight
This XPath expression will match all nodes whose class attribute is exactly equal to "myclass". In other words, <div class="foo myclass"/> would _not_ match. The XPath would need to be modified with `contains()` plus spaces delimiters to avoid substring matches such as "myclass2"
Josh Davis