新项目,大概情况是这样的:可能存在多国、不同语种使用者,比喻有中文、繁体中文,韩文、日本等等,开发时选择了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编码,故做以下设置

//输出BOM
echo(chr(255).chr(254));
echo(mb_convert_encoding($content,"UTF-16LE","UTF-8"));

各种语言正常显示

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

<?php
/**
 *导出到CSV文件
 * @param $data   导出数组
 * @param $file_name 文件名
 */
function export_csv($data,$file_name='')
{

    $file_name = $file_name.'_'.date('YmdHi').'.csv';
    $encoded_filename  = urlencode($file_name);
        $encoded_filename  = str_replace("+","%20",$encoded_filename );
    $content = array_to_string($data);
    header('Cache-control: private');
    //判断浏览器,输出双字节文件名不乱码
    $ua = $_SERVER["HTTP_USER_AGENT"];
    if (preg_match("/MSIE/", $ua)) {
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
    }
    else if (preg_match("/Firefox/", $ua)) {
        header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');
    }
    else {
        header('Content-Disposition: attachment; filename="' . $file_name . '"');
    }
    if(function_exists('mb_convert_encoding')){
        header('Content-type: text/csv; charset=UTF-16LE');
        //输出BOM
        echo(chr(255).chr(254));
        echo(mb_convert_encoding($content,"UTF-16LE","UTF-8"));
        exit;
    }
}
/**
 *导出数据转换
 * @param $result
 */
function array_to_string($result)
{
    if(empty($result)){
        return i("没有符合您要求的数据!^_^");
    }
    $size_result = count($result);
    for($i = 0 ; $i < $size_result ;  $i++) {
        $data .= $result[$i]."\n";
    }
    return $data;
}
?>

posted on 2016-03-15 12:30  kclteam  阅读(10391)  评论(0编辑  收藏  举报