//生成csv文件,完美解决中文乱码和大数据失真问题
if(!function_exists('toCSV')) {
function toCSV(array $data, array $colHeaders, $asString = false) {
$stream = ($asString)
? fopen("php://temp/maxmemory", "w+") //生成临时csv
: fopen("php://output", "w");//浏览器下载
//在写入的第1行第1列的开头加bom,解决excel打开乱码问题
$bom = chr(0xEF).chr(0xBB).chr(0xBF);
if (!empty($colHeaders)) {//标题的第1行第1列,开头加bom
$colHeaders[0] = $bom.$colHeaders[0];
fputcsv($stream, $colHeaders);
} else {//内容的第1行第1列,开头加bom
foreach ($data as $key => $record) {
$data[$key] = $bom.$record;
break;
}
}
foreach ($data as $key => $record) {
//数字超过15位加"\t"防止失真
foreach ($record as $k => $v) {
if (is_numeric($v) && strlen($v) > 15) {
$record[$k] = "\t".$v;
}
}
fputcsv($stream, $record);
}
if ($asString) {
rewind($stream);
$returnVal = stream_get_contents($stream);
$returnVal = iconv('utf-8', 'gbk//ignore', $returnVal);
fclose($stream);
return $returnVal;
} else {
fclose($stream);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.time().'.csv"');
}
}
|