PHP5: Find Root Node in DOMDocument

試著忘記壹切 提交于 2019-11-29 09:28:00
PatrikAkerstrand

According to the PHP docs DOMElement is a subclass of DOMNode, so it should inherit the hasChildNodes()-method.

DOMElement extends DOMNode.

You get the Root DOMElement by $d->documentElement.

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

Prior to php 5.1.3 this guy has it licked

https://macfoo.wordpress.com/2009/06/03/getting-the-root-node-from-an-xml-string

/**
 * function getXMLRootNode
 * @param string An xml string
 * @return string Return XML root node name
 */

function getXMLRootNode($xmlstr)
{
 // Create DOM model
 $doc = new DOMDocument();

 // Load the XML string
 if(!$doc->loadXML($xmlstr))
 {
 throw new Exception('Unable to parse XML string');
 }

 // Find the root tag name
 $root = $doc->documentElement;

 if(!isset($root))
 {
 throw new Exception('Unable to find XML root node');
 }

 if(!isset($root->nodeName))
 {
 throw new Exception('Unable to find XML root node name');
 }

 return $root->nodeName;
}

Cross Posted to SO Questions that I hit while trying to find how to do this pre 5.1.3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!