titel
titel

Reputation: 3502

Recursively find all the nodes from an XML having a given argument with PHP / simpleXML

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.

Upvotes: 0

Views: 1046

Answers (1)

Jack Sleight
Jack Sleight

Reputation: 17118

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.)

Upvotes: 3

Related Questions