如何将 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);

有人帮忙吗?


MYYA
浏览 79回答 1
1回答

慕的地10843

首先,请查看文档中此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">&nbsp; &nbsp; <ns0:TYPE>EXRCTRFRESP</ns0:TYPE>&nbsp; &nbsp; <ns0:TXNSTATUS>200</ns0:TXNSTATUS>&nbsp; &nbsp; <ns0:DATE>02/02/20</ns0:DATE>&nbsp; &nbsp; <ns0:EXTREFNUM>20200202192308729Af9cWtvg3W</ns0:EXTREFNUM>&nbsp; &nbsp; <ns0:TXNID>R200202.1923.250008</ns0:TXNID>&nbsp; &nbsp; <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);// OutputsArray(&nbsp; &nbsp; [TYPE] => EXRCTRFRESP&nbsp; &nbsp; [TXNSTATUS] => 200&nbsp; &nbsp; [DATE] => 02/02/20&nbsp; &nbsp; [EXTREFNUM] => 20200202192308729Af9cWtvg3W&nbsp; &nbsp; [TXNID] => R200202.1923.250008&nbsp; &nbsp; [MESSAGE] => R200202.1923.250008 confirmed.&nbsp;)顺便说一句,您也可以使用xml文件执行此操作。在这种情况下,您需要以相同的方式使用此函数。simplexml_load_file()<?php$xml_file = 'your_xml_file_location.xml';$xml = simplexml_load_file($xml_file, "SimpleXMLElement", LIBXML_NOCDATA, 'ns0', true);
打开App,查看更多内容
随时随地看视频慕课网APP