Parse XML with multiple namespace to JSON - PHP

独自空忆成欢 提交于 2019-12-11 17:05:41

问题


I want to access the XML and parse it as JSON.

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ser='http://service.billing.org/'>
  <soapenv:Header />
  <soapenv:Body>
  <ser:processTrans>
     <xmlValue>
         <![CDATA[
            <ebpacket> 
                <head> 
                    <packettype> UserAuthorization</packettype>
                    <staffcode> ePay_UserName  </staffcode> 
                    <pwd>  ePay_Password </pwd>
                </head> 
                <body>
                    <email> _username  </email>
                    <loginpwd>  _password  </loginpwd>
                    <deviceid>  DeviceId  </deviceid>
                </body>
            </ebpacket>
        ]]>
    </xmlValue>
  </ser:processTrans>

I am able to access the values the following way:

$xml_str = str_replace(PHP_EOL, '', $xmlstr);
$xml = SimpleXML_Load_String($xml_str,'SimpleXMLElement', LIBXML_NOCDATA, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('ser', 'http://service.billing.org');
$j_obj = json_encode($xml->xpath('//soapenv:Body'));

The problem is that, XML structure is not known in advance. Hence, I cannot specifically access through the namespace. Unless I specify the namespace $xml->xpath('//soapenv:Body'), it does not return the expected result.


回答1:


I think your getting the two namespaces mixed up, your trying to register the soapenv prefix with the URI used for ser. Not that this affects the code, but it may not give what your expecting.

As for not knowing the namespaces in advance, in SimpleXML you can use getDocNamespaces() to fetch the namespaces from the document and then loop through and register them against the prefixes. So the following code fetches the XML content of the Body...

$xml_str = str_replace(PHP_EOL, '', $xmlstr);
$xml = simplexml_load_string($xml_str,'SimpleXMLElement', LIBXML_NOCDATA);
$ns = $xml->getDocNamespaces(true);
foreach ( $ns as $prefix => $URI )   {
    $xml->registerXPathNamespace($prefix, $URI);
}
$j_obj = json_encode($xml->xpath('//soapenv:Body/*'));


来源:https://stackoverflow.com/questions/48299894/parse-xml-with-multiple-namespace-to-json-php

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