如何强制浏览器下载我在PHP中创建的csv文件?
我试过
$result = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('aaa', 'bbb')
);
$filename = 'result_file.csv';
header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Length: " . strlen($result));
echo $result;
exit;
但是csv文件充满了PHP错误
答案 0 :(得分:3)
在这里,大家和我自己的赞美。
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=result_file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$data = array(
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('aaa', 'bbb')
);
outputCSV($data);
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
}