直接上代碼~~~
function Export($data,$FileName)
{
set_time_limit(0);
$columns = [
'學號', '姓名', '年級', '學科', '分數'
];
$FileName = $FileName."csv";
//設置headers
header('Content-Description: File Transfer');//
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'. $FileName .'"');// MIME 協議的擴展,MIME 協議指示 MIME 用戶代理如何顯示附加的文件。當 Internet Explorer 接收到頭時,它會激活文件下載對話框,它的文件名框自動填充了頭中指定的文件名
header('Expires: 0');//緩存過期時間;
header('Cache-Control: must-revalidate');//強制頁面不緩存與no-cache相同,但更嚴格
header('Pragma: public');//
$fp = fopen('php://output', 'a');//打開output流
mb_convert_variables('GBK', 'UTF-8', $columns);
fputcsv($fp, $columns);//將數據格式化爲CSV格式並寫入到output流中
foreach($data as $v) {
mb_convert_variables('GBK', 'UTF-8', $v);
fputcsv($fp, $v);
}
$data = null;
unset($data);
ob_flush();
flush();
fclose($fp);
exit();
}
$data= array(
array('5','小米', '1', '語文', '88'),
array('1','小明1', '1', '語文', '99'),
array('2','小紅2', '1', '語文', '89'),
array('3','小花3', '2', '語文', '98'),
array('4','小剛4', '3', '語文', '98')
);
Export($data,'students');