将具有多个命名空间的 XML 解析为 JSON - PHP [英] Parse XML with multiple namespace to JSON - PHP

查看:37
本文介绍了将具有多个命名空间的 XML 解析为 JSON - PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问 XML 并将其解析为 JSON.

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

问题在于,XML 结构是事先不知道的.因此,我无法通过命名空间专门访问.除非我指定命名空间 $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.

推荐答案

我认为您混淆了两个命名空间,您试图将 soapenv 前缀与用于 ser 的 URI 注册.并不是说这会影响代码,但它可能无法满足您的期望.

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.

对于事先不知道命名空间的情况,在 SimpleXML 中,您可以使用 getDocNamespaces() 从文档中获取命名空间,然后循环并根据前缀注册它们.所以下面的代码获取Body的XML内容...

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/*'));

这篇关于将具有多个命名空间的 XML 解析为 JSON - PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆