轉換代碼如下
//數組轉XML function arrayToXml($arr) { $xml = "<xml>"; foreach ($arr as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; } } $xml.="</xml>"; return $xml; } //將XML轉為array function xmlToArray($xml) { //禁止引用外部xml實體 libxml_disable_entity_loader(true); $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $values; }
Array轉XML
$money = 101; $sender = "吾愛編程"; $obj2 = array(); $obj2['wxappid'] = APPID; $obj2['mch_id'] = MCHID; $obj2['mch_billno'] = MCHID.date('YmdHis').rand(1000, 9999); $obj2['client_ip'] = $_SERVER['REMOTE_ADDR']; $obj2['re_openid'] = $openid; $obj2['total_amount'] = $money; $obj2['min_value'] = $money; $obj2['max_value'] = $money; $obj2['total_num'] = 1; $obj2['nick_name'] = $sender; $obj2['send_name'] = $sender; $obj2['wishing'] = "恭喜發財"; $obj2['act_name'] = "吾愛編程送紅包"; $obj2['remark'] = "關注公眾賬號";
轉換後
<xml> <wxappid><![CDATA[wx1b7559b818e3c123]]></wxappid> <mch_id>1235571234</mch_id> <mch_billno>1235571234201605241726128109</mch_billno> <client_ip><![CDATA[127.0.0.1]]></client_ip> <re_openid><![CDATA[oiPuduGV7gJ_MOSfAWpVmhhgXh-U]]></re_openid> <total_amount>101</total_amount> <min_value>101</min_value> <max_value>101</max_value> <total_num>1</total_num> <nick_name><![CDATA[吾愛編程]]></nick_name> <send_name><![CDATA[吾愛編程]]></send_name> <wishing><![CDATA[恭喜發財]]></wishing> <act_name><![CDATA[吾愛編程送紅包]]></act_name> <remark><![CDATA[關注公眾賬號]]></remark> </xml>
XML轉為Array
<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[發放成功]]></return_msg> <result_code><![CDATA[SUCCESS]]></result_code> <err_code><![CDATA[MONEY_LIMIT]]></err_code> <err_code_des><![CDATA[發放成功]></err_code_des> <mch_billno><![CDATA[1235571234201605241651123985]]></mch_billno> <mch_id>1235571234</mch_id> <wxappid><![CDATA[wx1b7559b818e3c123]]></wxappid> <re_openid><![CDATA[oiPuduGV7gJ_MOSfAWpVmhhgXh-U]]></re_openid> <total_amount>1</total_amount> </xml>
轉換後
array(10) { ["return_code"]=> string(7) "SUCCESS" ["return_msg"]=> string(12) "發放成功" ["result_code"]=> string(7) "SUCCESS" ["err_code"]=> string(11) "MONEY_LIMIT" ["err_code_des"]=> string(12) "發放成功" ["mch_billno"]=> string(28) "1235571234201605241651123985" ["mch_id"]=> string(10) "1235571234" ["wxappid"]=> string(18) "wx1b7559b818e3c123" ["re_openid"]=> string(28) "oiPuduGV7gJ_MOSfAWpVmhhgXh-U" ["total_amount"]=> string(1) "1" }*