Access an element's parent with PHP's SimpleXML?

thisismyname picture thisismyname · Feb 1, 2010 · Viewed 26.6k times · Source

I'm iterating through a set of SimpleXML objects, and I can't figure out how to access each object's parent node. Here's what I want:

$divs = simplexml->xpath("//div");
foreach ($divs as $div)
{
   $parent_div = $div->get_parent_node(); // Sadly, there's no such function.
}

Seems like there must be a fairly easy way to do this.

Answer

nickf picture nickf · Feb 1, 2010

You could run a simple XPath query to get it:

$parent_div = $div->xpath("parent::*");

And as this is Simplexml and it only has element and attribute nodes and a parent node can only be an element and never an attribute, the abbreviated syntax can be used:

$parent_div = $div->xpath("..");

(via: Common Xpath Cheats - SimpleXML Type Cheatsheet (Feb 2013; by hakre) )