解釋幾個請求頭:
- Content-type:內容類型
- Content-Disposition:設置爲瀏覽器顯示(Disposition)或作爲文件下載(attachment)
- Expires:設置瀏覽器緩存有效期,0爲不緩存
- Cache-Control:設置請求和響應的緩存機制指令,指令均爲單向,must-revalidate表示每次使用緩存前校驗有效期,post-check=0,pre-check=0是IE5.0纔有的防cache聲明
- Content-Transfer-Encoding:內容傳輸編碼
- Pragma:HTTP1.0客戶端向後兼容,與 Cache-Control: no-cache 作用相同
<?php
function exportCsv($data, $title, $filename = '報表')
{
foreach ($title as $k => $v) {
$title[$k] = iconv("UTF-8", "GBK//IGNORE", $v);
}
$csv_data = '';
$csv_data .= implode(',', $title) . PHP_EOL;
foreach ($data as $k => $v) {
foreach ($v as $i => $item) {
$v[$i] = iconv("UTF-8", "GBK//IGNORE", $item);
}
$csv_data .= implode(',', $v) . PHP_EOL;
}
header('Content-type:csv');
header('Content-Disposition: attachment; filename=' . $filename . '.csv');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
}
else
{
header('Cache-Control: no-store, max-age=0, no-cache');
header('Pragma: no-cache');
}
echo $csv_data;
}
$title = [
'第一列',
'第二列',
'第三列',
];
$data = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
];
exportCsv($data, $title, '報表');