PHP:XML到JSON失败 [英] PHP: XML to JSON fails

查看:114
本文介绍了PHP:XML到JSON失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用json_encode将XML(simpleXML)转换为JSON时,它适用于没有名称空间的XML. 例如:

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>

当我像下面那样用属性转换XML时,json_encode返回一个空的json:

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

推荐答案

通读之后,我发现您必须注册名称空间才能访问带有名称空间前缀的节点. 例如:

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

这将仅返回带有Head和Body的XML对象.它将返回带有其他前缀的所有节点.在上面的示例中,它将不返回前缀"ser"下的节点.返回的XML是;

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将是一个数组,其所有属性都在节点'ser:processTrans'下.

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

这篇关于PHP:XML到JSON失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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