Mauritz Swanepoel Mauritz Swanepoel - 5 months ago 28
PHP Question

simplexml_load_string function not loading XML file in PHP

I am busy with an EPP registration module which returns XML via a stream service.

The XML returns fine but I am unable to get load using PHP's simple_xml_load_string or new SimpleXMLElement to correctly load the XML so that I can use the data as an object.

I am however able to return the XML back using asXML() so it would appear that the XML is loaded, I am just not able to get access to any of the values within the object. A print_r() of the object also returns an empty object (from what I understand this is correct).

Here is a sample of a login result:

<epp:epp xmlns:epp="urn:ietf:params:xml:ns:epp-1.0">
<epp:response>
<epp:result code="1000">
<epp:msg>Access granted</epp:msg>
</epp:result>
<epp:trID>
<epp:clTRID>ABC-123456</epp:clTRID>
<epp:svTRID>OTE-EPP-155A695A3C9-717E</epp:svTRID>
</epp:trID>
</epp:response>
</epp:epp>


What I need to get access to is the result code above.

Here is sample PHP I have tried:

// Note that the $var property contains the XML exactly as it is above.
$result = simplexml_load_string($var);
echo $result->response->msg; // Nothing
echo $result->asXML(); // Returns the XML correctly.
$result = new SimpleXMLElement($var);
print_r($result); // Returns an empty object.
echo $result->response->msg; // Nothing
echo $result->toXML(); // Returns the XML correctly.


Any ideas would greatly be appreciated :)

Answer

According to the manual simplexml_load_string has the following parameters:

SimpleXMLElement simplexml_load_string ( string $data [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

Therefore, I believe that you can load your XML this way :

simplexml_load_string($var, "SimpleXMLElement", 0, "epp", true);

I hope this works for you.