PHP: XML to JSON fails

自作多情 提交于 2019-12-14 03:06:26

问题


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);

回答1:


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'.



来源:https://stackoverflow.com/questions/48280427/php-xml-to-json-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!