一.array 转xml
1.$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredSeqNo'] = "1";//被保险人序列号
$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredName'] = "小红";//被保险人姓名
$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredIdType'] = "01";//被保险人证件类型
$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredIdNo'] = "3303047";//被保险人证件号
$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredBirthday'] = "1944-11-30";//被保险人生日
$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredIdMobile'] = "15238300274";//被保险人手机号码
$insurance_data['ApplyInfo']['PolicyInfos']['PolicyInfo']['Insureds']['Insured']['InsuredAddress'] = "浙江温州永嘉";//关系人地址
$insurance_xml = $this->xml_encode($insurance_data,"GB2312");
/**
* XML编码
* @param mixed $data 数据
* @param string $encoding 数据编码
* @param string $root 根节点名
* @return string
*/
function xml_encode($data, $encoding='utf-8') {
$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
$xml .= $this->data_to_xml($data);
return $xml;
}
/**
* 数据XML编码
* @param mixed $data 数据
* @return string
*/
function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
if($key==="ExtendInfo"){
$xml .= "<$key key='callbackPage'>";
}else if(is_numeric($key)){
$xml .= "";
}else{
$xml .= "<$key>";
}
$xml .= ( is_array($val) || is_object($val)) ? $this->data_to_xml($val) : $val;
list($key, ) = explode(' ', $key);
//去数字的<1></1>
if(is_numeric($key)){
$xml .= "";
}else{
$xml .= "</$key>";
}
}
return $xml;
}
二。xml转array
$result='<?xml version="1.0" encoding="GB2312" standalone="yes"?>
<ApplyInfo>
<PayOnlineInfo>
<PayType>alipay</PayType>
<PayAmount>1111</PayAmount>
<PayResult>00</PayResult>
<PayTime>2018-02-02 16:21:07</PayTime>
</PayOnlineInfo>
</ApplyInfo>';
$result=str_replace("GB2312", "UTF-8", $result); //将字符串的编码从GB2312转到UTF-8
//echo $result;
//xml转array
$pos = strpos($result, 'xml');
if (!$pos) {
die("不是xml字符串!");
}
$postObj=simplexml_load_string($result,'SimpleXMLElement', LIBXML_NOCDATA);//echo $postObj;
$jsonStr = json_encode($postObj);
$jsonArray = json_decode($jsonStr,true);