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

报告相同问题?

悬赏问题

  • ¥15 基于ucc28019的pfc电路中芯片一直不工作
  • ¥15 yolov8在3588板子端c++推理报错
  • ¥50 unitywebrequest分段下载导致报错,如何解决?
  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能