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.
Note that you can extend SimpleXML to make it so. For example:
And now all you have to do is modify the code you use to create your SimpleXMLElement in the first place:
The best part is that SimpleXML will automatically and transparently return
my_xml
objects for this document, so you don't have to change anything else, which makes yourget_parent_node()
method chainable:You could run a simple XPath query to get it:
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:
(via: Common Xpath Cheats - SimpleXML Type Cheatsheet (Feb 2013; by hakre) )
If memory serves, an
xpath()
call returns one or moreSimpleXMLElements
. If that's the case, then you may be able to use something like: