Search code examples
phpxmldomsimplexml

simplexml_load_string return empty result


It may be simple, but I am kind of stuck. I want to convert an XML string into PHP object. My XML string is:

$a = '<?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <soap:Body>
                <VerifyTxnResponse xmlns="http://www.exmlplekhe.com/">
                    <VerifyTxnResult>BID &lt;11467&gt;</VerifyTxnResult>
                </VerifyTxnResponse>
            </soap:Body>
        </soap:Envelope>';

I have tried var_dump(simplexml_load_string($a));, but it returns empty SimpleXMLElement object. I want to get VerifyTxnResult node. I think, &lt;11467&gt; is causing the problem. What may be the possible solution?

Thanks.


Solution

  • I want to get VerifyTxnResult node

    The simplexml_load_string function returns an instance of SimpleXMLElement which is actually not empty for the XML you posted.

    Register the namespace and fetch the node with xpath method:

    $se = simplexml_load_string($a);
    
    $se->registerXPathNamespace('r', 'http://www.nibl.com.np/');
    
    foreach ($se->xpath('//r:VerifyTxnResult') as $result) {
      var_dump((string)$result);
    }
    

    Sample Output

    string(11) "BID <11467>"