Sep 20, 2018

PHP: simplexml_load_string return empty

Need to record down what I had solved for some tricky PHP issue.   
If not, when I hit again, I forgot what is the solution.  ( Old age nowadays)

A simple XML as below, when put into simplexml_load_string function, it is returning empty object. 

$sXML = '<soap:envelope 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" >
   <soap:body>
        <abc_rq primarylangid="en-us" 
timestamp="2018-09-20T15:27:02.728923+08:00" 
version="0">
            <daterange end="2018-09-28" start="2018-09-25"></daterange>
            <quantity>1</quantity>
            <hotelname>Saya Anak Malaysia</hotelname>
            <hotelcode>SAM_01</hotelcode>
        </abc_rq>
    </soap:body>
</soap:envelope>';


$oXML = simplexml_load_string($sXML, "SimpleXMLElement", LIBXML_NOCDATA);

echo "\n oXML:<pre>";
print_r($oXML);
echo "</pre>";
Output is 
oXML:
SimpleXMLElement Object
(
)

The culprit is on xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
I had tried to add name space into simplexml_load_string, something like below.

$oXML = simplexml_load_string($sXML, "SimpleXMLElement", LIBXML_NOCDATA, 
"http://schemas.xmlsoap.org/soap/envelope/", false);

Output become like this:
SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
        )

)

Because only Body element got soap in front  e.g 
So how???

Here the solution.

$sXML = str_replace('xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"',
 '', $sXML);
$oXML = simplexml_load_string($sXML, "SimpleXMLElement", LIBXML_NOCDATA);

Remove the Name Space in the XML before calling simplexml_load_String.  Plus remove the name space in simplexml_load_string.

Output become nicely now. 

oXML:
SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
            [Abc_RQ] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [TimeStamp] => 2018-09-20T15:27:02.728923+08:00
                            [PrimaryLangID] => en-us
                            [Version] => 0
                        )

                    [DateRange] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [Start] => 2018-09-25
                                    [End] => 2018-09-28
                                )

                        )

                    [Quantity] => 1
                    [HotelName] => Saya Anak Malaysia
                    [HotelCode] => SAM_01
                )

        )

)

No comments: