我在控制台中成功获得了所需的输出,但浏览器没有自动下载CSV文件。
header('Content-Type: application/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
$output = fopen('php://output', 'rb');
// output the column headings
fputcsv($output, array('Procedure Name', 'Totals'));
foreach ($rows as $row){
fputcsv($output, $row);
}
fopen($filename);
fclose($output);
答案 0 :(得分:0)
呸,这在评论中是不守规矩的。我更进一步,让它循环遍历这些值!
// Set headers
header('Content-Type: text/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
// Column titles
echo 'Procedure Name,Totals' . "\n"; // Don't forget the newlines!
// Data
foreach ($rows as $row) {
foreach ($row as $index => $value) {
echo $value;
if ($index < count($row) - 1) {
echo ',';
}
}
echo "\n";
}
您也可以将其缓冲到文件中,以便使用fputcsv
。这几乎与您当前的代码完全一样,但最后您有echo file_get_contents($the_buffer_file);
重点是您需要做的就是以CSV格式输出数据,即用逗号分隔值,新行是新行。使用引号(未在我的代码中显示)转义值也是明智的。
答案 1 :(得分:0)
我的浏览器中运行的示例:
$csv= '"Procedure Name", Totals'."\n";
$rows= array(
array('aaa', 'bbb'),
array('123', '456')
);
foreach ($rows as $row){
$csv .= implode(",",$row)."\n";
}
$filename= 'Totals Report for '.$name.' All-Time.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
die($csv);