导出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));
网友评论