如何将XML转换为JSON

用户名

如何将此XML转换为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>

我尝试这样做,但返回空数组。

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

有人帮忙吗?

unclexo

首先,请在文档中查看此PHP的内置函数simplexml_load_string,以了解此函数采用哪些参数,为什么?由于您的xml字符串使用名称空间,因此您必须提供名称空间作为第4个参数。看下面的代码:

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

顺便说一句,您也可以使用xml文件来实现。在这种情况下,您需要以simplexml_load_file()相同的方式使用此功能

<?php

$xml_file = 'your_xml_file_location.xml';
$xml = simplexml_load_file($xml_file, "SimpleXMLElement", LIBXML_NOCDATA, 'ns0', true);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档