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

前端之家收集整理的这篇文章主要介绍了解决php array数组生成xml文件汉字编码问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

  1. function array2xml($array$xml = false){  
  2.     if($xml === false){  
  3.         $xml = new SimpleXMLElement('<root/>');  
  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->addChild($key));  
  2.         }else{  
  3.              
  4. //$value=utf8_encode($value);  
  5.    
  6.             if (preg_match("/([x81-xfe][x40-xfe])/"$value$match)) {  
  7.                 $value = iconv('gbk''utf-8'$value);    
  8. //判断是否有汉字出现  
  9.             }  
  10.             $xml->addChild($key$value);  
  11.         }  
  12.     }  
  13.     return $xml->asXML();  

猜你在找的PHP相关文章