PHP5: Find Root Node in DOMDocument
Solution 1
According to the PHP docs DOMElement is a subclass of DOMNode, so it should inherit the hasChildNodes()
-method.
Solution 2
DOMElement extends DOMNode.
You get the Root DOMElement by $d->documentElement.
Solution 3
DOM Model- The W3C has broken down the DOM into a tree structure of nodes of varying types. The Node interface is the base interface for all elements. All objects implementing this interface expose methods for dealing with children.
$dom=new DomDocument;
$dom->Load("file.xml");
$root=$dom->documentElement; // Root node
Related videos on Youtube
Nishan
Professional Web Developer since 2001, amateur developer since 198x. Eating and breathing JavaScript and PHP in my day-to-day live, but have seen a lot in my 30+ years of code-juggling. Adobe Certified Expert - Adobe Analytics Developer
Updated on July 09, 2022Comments
-
Nishan almost 2 years
I have a PHP5 DOMDocument and I try to find the root node (not the root element).
Example:
<test> <element> <bla1>x</bla1> <bla2>x</bla2> </element> <element> <bla1>y</bla1> <bla2>y</bla2> </element> <element> <bla1>z</bla1> <bla2>z</bla2> </element> </test>
I want to get the DOMNode of "test" so that I can call - for example - hasChildNodes. I can get the "documentElement", but that's a DOMElement. Maybe I can go from there?
$d = DOMDocument::loadXML($xml); // [... do some stuff here to find document's root node ...] if ($rootnode->hasChildNodes()) echo 'yayy!'
Who can fill the gap? I seem to be blind.
(Obviously it's not only hasChildNodes I want to call - so NO, it doesn't help to find another method to find out if the document contains stuff. That's just for my simple example. I need a DOMNode at the end.)
-
Nishan almost 15 yearsHmmm, okay, that's actually true... And if I don't send my ->documentElement to a function, everything seems to work correctly... The function call looses something on it's way... Now on to find that...
-
Angel.King.47 over 12 yearsThis should actually be the ticked answer!
-
gawpertron over 11 yearshere is the documentation for this property php.net/manual/en/…
-
Ben over 10 yearsI'll save someone a click. The above documentation says:
This is a convenience attribute that allows direct access to the child node that is the document element of the document.