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

时间:2017-11-09 10:03:21

标签: php xml

我试图从xml属性中获取值。但它只返回3个值“resCode,message,Pid”无法获得“orderno,orderdate”。这是我的xml值,它来自$ data变量。

 <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);    
 print_r(xml2array($xmlData));

2 个答案:

答案 0 :(得分:1)

是的,这是获取xml内容的另一种方式,例如: -

<?php
    $mystring=' <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 = simplexml_load_string($mystring, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    $final_array = json_decode($json,TRUE);
    print_r($array);
?>

答案 1 :(得分:0)

由于某些元素包含名称空间,因此它们与简单的json编码位不兼容。作为添加这些额外值的快速方法,我已经完成了......

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

这给...

Array
(
    [rescode] => 111
    [messages] => Array
        (
            [message] => Success
        )

    [Pid] => 4555544
    [orderno] => A2131589
    [orderdate] => 20171109
)