drvkf88226 2017-11-09 10:03
浏览 90
已采纳

如何使用php从Xml属性获取值

I am trying to get value from xml attributes. But it returns only 3 values "resCode,message,Pid" not able to get "orderno,orderdate". This is my xml value which is coming in $data variable.

 <ns2:orderresponse xmlns="http://vo.services.order.com/base"  xmlns:ns2="http://vo.services.order.com/createorder/response">
 <rescode>111</rescode>
 <messages><message>Success</message></messages>
 <Pid>4555544</Pid>
  <ns2:orderno>A2131589</ns2:orderno>
 <ns2:orderdate>20171109</ns2:orderdate>
 </ns2:orderresponse>

I am using this to get xml attributes value.

 $xmlData = new SimpleXMLElement($data);    
 print_r(xml2array($xmlData));
  • 写回答

2条回答 默认 最新

  • dongyiyu882684 2017-11-09 13:26
    关注

    As some elements include namespaces, they don't work well with the simple json encode bit. As a quick way of just adding in those extra values, I've done...

    <?php
    error_reporting ( E_ALL );
    ini_set ( 'display_errors', 1 );
    
    $data  = <<<XML
     <ns2:orderresponse xmlns="http://vo.services.order.com/base"  xmlns:ns2="http://vo.services.order.com/createorder/response">
     <rescode>111</rescode>
     <messages><message>Success</message></messages>
     <Pid>4555544</Pid>
      <ns2:orderno>A2131589</ns2:orderno>
     <ns2:orderdate>20171109</ns2:orderdate>
     </ns2:orderresponse>
    XML;
    
    $xmlData = new SimpleXMLElement($data);
    $json = json_encode($xmlData);
    $final = json_decode($json,TRUE);
    
    foreach ( $xmlData->children("http://vo.services.order.com/createorder/response") as $ns)    {
        $final[$ns->getName()] = (string)$ns;
    }
    
    print_r($final);
    

    This gives...

    Array
    (
        [rescode] => 111
        [messages] => Array
            (
                [message] => Success
            )
    
        [Pid] => 4555544
        [orderno] => A2131589
        [orderdate] => 20171109
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器