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;
}
Categories: PHP, Programming





