testingexpert
testingexpert

Reputation: 53

How to get value from Xml attributes using php

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

Upvotes: 0

Views: 307

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57131

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
)

Upvotes: 0

Ravi Sharma
Ravi Sharma

Reputation: 487

yes here is another way to get xml content look below example :-

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

Upvotes: 1

Related Questions