Dilani
Dilani

Reputation: 553

PHP: XML to JSON fails

When I try to convert XML(simpleXML) to JSON with json_encode, It works for XML without namesapce. For Example:

<ebpacket> 
   <head> 
      <packettype> UserAuthorization</packettype>
      <staffcode> UserName  </staffcode> 
      <pwd>  Password  </pwd> 
      <env>  Evnironment  </env> 
   </head> 
</ebpacket>

When I convert XML like below with attributes, json_encode returns an empty json:

<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/>
 <soapenv:Header />
 <soapenv:Body>
  <ser:processTrans>
     <xmlValue>
            <ebpacket> 
                <head> 
                    <packettype> UserAuthorization</packettype>
                    <staffcode> UserName  </staffcode> 
                    <pwd> Password  </pwd> 
                    <env>  Evnironment  </env> 
                </head> 
            </ebpacket>
    </xmlValue>
  </ser:processTrans>

The code block I am using is:

        $xml_str = str_replace(PHP_EOL, '', $xmlstr);
        $xml = simplexml_load_string($xml_str,'SimpleXMLElement',LIBXML_NOCDATA);
        $json_object = json_encode($xml, JSON_PRETTY_PRINT);

Upvotes: 0

Views: 627

Answers (1)

Dilani
Dilani

Reputation: 553

After reading through, I figured out that you have to register your namespace to access the nodes with namespace prefix. For example:

$xml= SimpleXML_Load_String($xml_str,'SimpleXMLElement', LIBXML_NOCDATA, "http://schemas.xmlsoap.org/soap/envelope/");

This will return an XML object only with Head and Body. It will return any nodes with other prefixes. In the above example, it will not return nodes under the prefix 'ser'. Returned XML would be;

<Header></Header>
<Body></Body>

To be able to access other nodes, you have to use register the namespace and query it.

$xml->registerXPathNamespace('ser', 'http://w3c.soap.envelope.org/');
$result = $xml->xpath('//ser:*');

$result would be an array with all attributes under node 'ser:processTrans'.

Upvotes: 1

Related Questions