Getting the root node from an XML string

PHPs SimpleXML is great for parsing xml files. The downside is that it does not return the root node name. I wrote this function that gets the name.


/**
 * 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;
}

Advertisements

One thought on “Getting the root node from an XML string

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s