//输出BOM
echo(chr(255).chr(254));
echo(mb_convert_encoding($content,"UTF-16LE","UTF-8"));
各种语言正常显示
以下是完整function,支持双字节文件名(比如日文或中文文件名)不乱码
<?php
function export_csv($data,$file_name='')
{
$file_name = $file_name.'_'.date('YmdHi').'.csv';
$encoded_filename = urlencode($file_name);
$encoded_filename = str_replace("+"," ",$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;
}
}
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;
}
?>
注意点:
1、导出的分隔符不能用CSV的默认","而要用"\t" 否则表格单元不能正确切分
导出的CSV文件的导入功能,需要判断相应的编码UTF-16LE,反解码为UTF-8,方法参照:
http://www.iteye.com/topic/565929
if(getFileEncoding($data)==='UTF-16LE'){
$data=mb_convert_encoding($data,"UTF-8","UTF-16LE");
}