频道栏目
首页 > 资讯 > 数组 > 正文

解决php array数组生成xml文件汉字编码问题

16-01-06        来源:[db:作者]  
收藏   我要投稿

汉字在php应用中经常会给我们带来一些麻烦,今天在网上找到一段array数组转换成xml时发现汉字就为空了,后来gg了关天得出比较好的结果了,下面与大家分享,在 php 数组转xml我们在php中学会这样来写:

  1. function array2xml($array, $xml = false){  
  2.     if($xml === false){  
  3.         $xml = new SimpleXMLElement('');  
  4.     }  
  5.     foreach($array as $key => $value){  
  6.         if(is_array($value)){  
  7.             array2xml($value, $xml->addChild($key));  
  8.         }else{  
  9.             $xml->addChild($key, $value);  
  10.         }  
  11.     }  
  12.     return $xml->asXML();  
  13. }  
  14.    
  15. header('Content-type: text/xml');  
  16. print array2xml($array); 

当内容出现汉字时会出现为空的情况,解决办法是转编码处理,代码如下:  

  1. function array2xml($array, $xml = false){  
  2.     if($xml === false){  
  3.         $xml = new SimpleXMLElement('');  
  4.     }  
  5.     foreach($array as $key => $value){  
  6.         if(is_array($value)){  
  7.             array2xml($value, $xml->addChild($key));  
  8.         }else{  
  9.              
  10. //$value=utf8_encode($value);  
  11.    
  12.             if (preg_match("/([x81-xfe][x40-xfe])/", $value, $match)) {  
  13.                 $value = iconv('gbk', 'utf-8', $value);    
  14. //判断是否有汉字出现  
  15.             }  
  16.             $xml->addChild($key, $value);  
  17.         }  
  18.     }  
  19.     return $xml->asXML();  
相关TAG标签
上一篇:php数组提示Notice: Undefined offset解决办法
下一篇:php中向数组中插入一元素程序代码
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站