导出 csv 在 windows 下关上容易呈现乱码,须要在文件头部写入 BOM 标识,曾经封装成一个函数了
/**
* @param array $rows
* @param array $fields
* @param string $filename
*/
function kg_export_csv($rows, $fields = [], $filename = '')
{$filename = $filename ?: kg_uniqid();
header("Content-Type: text/csv");
header("Content-Disposition:filename={$filename}.csv");
$fp = fopen('php://output', 'w');
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
if ($fields) fputcsv($fp, $fields);
$index = 0;
foreach ($rows as $row) {if ($index == 1000) {
$index = 0;
ob_flush();
flush();}
$index++;
fputcsv($fp, $row);
}
要害局部,文件头写入 BOM 标识
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
原文链接:https://koogua.com/article/103