php xml转array array转xml

本文介绍了一种使用PHP实现的array与XML之间的转换方法。包括array数据结构转化为XML格式,以及如何将XML文档解析为array。适用于需要进行数据交换与处理的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值