Link to home
Start Free TrialLog in
Avatar of yami_rider
yami_rider

asked on

Get Root Node using DOMDocument in PHP 5

I am trying to get the root node of this XML using DOMDocument in PHP 5.

<diagnosis xmlns="http://checkout.google.com/schema/2" serial-number="8088c57b-bf00-4e83-b2d7-df9767da9140">
  <input-xml>
    <checkout-shopping-cart>
      <shopping-cart>
      </shopping-cart>
      <checkout-flow-support>
      </checkout-flow-support>
    </checkout-shopping-cart>
  </input-xml>
</diagnosis>

The root of the document should be "diagnosis" my code looks like this:
$dom_response = new DOMDocument();
    $boolresult = $dom_response->loadXML($diagnose_response);
    $root_element = $dom_response->getDocumentElement;
    $root_tag = $root_element->tagname;

The loadXML function returns TRUE, but when I call the property getDocumentElement it returns NULL.  

How would I go about getting the document root of the XML supplied?
 
ASKER CERTIFIED SOLUTION
Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No disrespect meant to the DOM, but this will do it with SimpleXML -  var_dump() works on the object, which makes debugging easier.
<?php // RAY_DOM_root_node.php
error_reporting(E_ALL);
echo "<pre>\n"; // READABILITY
 
 
// DATA FROM THE OP
$xml = '<diagnosis xmlns="http://checkout.google.com/schema/2" serial-number="8088c57b-bf00-4e83-b2d7-df9767da9140">
  <input-xml>
    <checkout-shopping-cart>
      <shopping-cart>
      </shopping-cart>
      <checkout-flow-support>
      </checkout-flow-support>
    </checkout-shopping-cart>
  </input-xml>
</diagnosis>';
 
// MAKE AN OBJECT AND VISUALIZE IT
$obj = SimpleXML_Load_String($xml);
// var_dump($obj);
 
// PREPEND THE CORRECT XML HEADERS
$new_xml = '<?xml version="1.0" ?><wrapper>' . $xml . '</wrapper>';
 
// MAKE AN OBJECT AND VISUALIZE IT
$new_obj = SimpleXML_Load_String($new_xml);
// var_dump($new_obj);
 
// MAKE AN ITERATOR TO EXTRACT THE TOP KEY
foreach ($new_obj as $key => $thing)
{
   var_dump($key);
}

Open in new window