php 多语言(UTF-8编码)导出Excel、CSV乱码解决办法之导出UTF-8编码的Excel、CSV

转自:  https://www.cnblogs.com/kclteam/p/5278926.html 

新项目,大概情况是这样的:可能存在多国、不同语种使用者,比喻有中文、繁体中文,韩文、日本等等,开发时选择了UTF-8编码,开发顺利,没有问题。昨天做了一个csv导出功能,导出的东西完全乱了:

设置mb_convert_encoding($content,"gb2312","UTF-8")的时候中文正常

设置mb_convert_encoding($content,"shift-jis","UTF-8")的时候日文正常

设置mb_convert_encoding($content,"UTF-8","UTF-8")的时候,都不正常

google了一下原因,我理解的大概意思是微软的csv等不支持uft-8编码,而是支持UTF-16LE编码,故做以下设置

1 //输出BOM
2 echo(chr(255).chr(254));
3 echo(mb_convert_encoding($content,"UTF-16LE","UTF-8"));
//或者其它 添加bom头的方式
//UTF-8的BOM头
$output = pack('H*','EFBBBF');

 

各种语言正常显示

以下是完整function,支持双字节文件名(比如日文或中文文件名)不乱码

 1 <?php
 2 /**
 3  *导出到CSV文件
 4  * @param $data   导出数组
 5  * @param $file_name 文件名
 6  */
 7 function export_csv($data,$file_name='')
 8 {
 9 
10     $file_name = $file_name.'_'.date('YmdHi').'.csv';
11     $encoded_filename  = urlencode($file_name);
12         $encoded_filename  = str_replace("+","%20",$encoded_filename );
13     $content = array_to_string($data);
14     header('Cache-control: private');
15     //判断浏览器,输出双字节文件名不乱码
16     $ua = $_SERVER["HTTP_USER_AGENT"];
17     if (preg_match("/MSIE/", $ua)) {
18         header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
19     }
20     else if (preg_match("/Firefox/", $ua)) {
21         header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');
22     }
23     else {
24         header('Content-Disposition: attachment; filename="' . $file_name . '"');
25     }
26     if(function_exists('mb_convert_encoding')){
27         header('Content-type: text/csv; charset=UTF-16LE');
28         //输出BOM
29         echo(chr(255).chr(254));
30         echo(mb_convert_encoding($content,"UTF-16LE","UTF-8"));
31         exit;
32     }
33 }
34 /**
35  *导出数据转换
36  * @param $result
37  */
38 function array_to_string($result)
39 {
40     if(empty($result)){
41         return i("没有符合您要求的数据!^_^");
42     }
43     $size_result = count($result);
44     for($i = 0 ; $i < $size_result ;  $i++) {
45         $data .= $result[$i]."\n";
46     }
47     return $data;
48 }
49 ?>

 

posted @ 2018-03-30 17:22  share112  阅读(539)  评论(0编辑  收藏  举报