How do I convert this XML to JSON
<?xml version="1.0" encoding="UTF-8"?>
<ns0:COMMAND xmlns:ns0="http://www.tibco.com/schemas/pinless/PINLESS.core/C2STransferBillPayment/Schema.xsd9">
<ns0:TYPE>EXRCTRFRESP</ns0:TYPE>
<ns0:TXNSTATUS>200</ns0:TXNSTATUS>
<ns0:DATE>02/02/20</ns0:DATE>
<ns0:EXTREFNUM>20200202192308729Af9cWtvg3W</ns0:EXTREFNUM>
<ns0:TXNID>R200202.1923.250008</ns0:TXNID>
<ns0:MESSAGE>R200202.1923.250008 confirmed. </ns0:MESSAGE>
</ns0:COMMAND>
I have tried doing this, but return empty array.
$string = '<?xml version="1.0" encoding="UTF-8"?><ns0:COMMAND xmlns:ns0="http://www.tibco.com/schemas/pinless/PINLESS.core/C2STransferBillPayment/Schema.xsd9"><ns0:TYPE>EXRCTRFRESP</ns0:TYPE><ns0:TXNSTATUS>200</ns0:TXNSTATUS><ns0:DATE>02/02/20</ns0:DATE><ns0:EXTREFNUM>20200202192308729Af9cWtvg3W</ns0:EXTREFNUM><ns0:TXNID>R200202.1923.250008</ns0:TXNID><ns0:MESSAGE>R200202.1923.250008 confirmed. </ns0:MESSAGE></ns0:COMMAND>';
$xmlObject = simplexml_load_string($string);
$jsonString = json_encode($xmlObject);
$jsonArray = json_decode($jsonString, true);
var_dump($jsonArray);
Anyone help?
First of all, please check out this PHP's built-in function simplexml_load_string in the doc to see what parameters does this function take and why? As your xml string is using namespace so you have to provide the namespace as the 4th argument. Look at the code below:
<?php
$xml_string = <<<EOR
<?xml version="1.0" encoding="UTF-8"?>
<ns0:COMMAND xmlns:ns0="http://www.tibco.com/schemas/pinless/PINLESS.core/C2STransferBillPayment/Schema.xsd9">
<ns0:TYPE>EXRCTRFRESP</ns0:TYPE>
<ns0:TXNSTATUS>200</ns0:TXNSTATUS>
<ns0:DATE>02/02/20</ns0:DATE>
<ns0:EXTREFNUM>20200202192308729Af9cWtvg3W</ns0:EXTREFNUM>
<ns0:TXNID>R200202.1923.250008</ns0:TXNID>
<ns0:MESSAGE>R200202.1923.250008 confirmed. </ns0:MESSAGE>
</ns0:COMMAND>
EOR;
$xml = simplexml_load_string($xml_string, "SimpleXMLElement", LIBXML_NOCDATA, 'ns0', true);
$json = json_encode($xml);
$array = json_decode($json, true);
echo '<pre>';
print_r($array);
// Outputs
Array
(
[TYPE] => EXRCTRFRESP
[TXNSTATUS] => 200
[DATE] => 02/02/20
[EXTREFNUM] => 20200202192308729Af9cWtvg3W
[TXNID] => R200202.1923.250008
[MESSAGE] => R200202.1923.250008 confirmed.
)
BTW you can do that using xml file too. In that case, you need to use this function simplexml_load_file()
the same way.
<?php
$xml_file = 'your_xml_file_location.xml';
$xml = simplexml_load_file($xml_file, "SimpleXMLElement", LIBXML_NOCDATA, 'ns0', true);