为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 XML 转换为 JSON

如何将 XML 转换为 JSON

PHP
MYYA 2022-09-03 16:36:01
如何将此 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);有人帮忙吗?
查看完整描述

1 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

首先,请查看文档中此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);



查看完整回答
反对 回复 2022-09-03
  • 1 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信