【发布时间】:2015-12-30 00:32:48
【问题描述】:
我正在尝试动态生成一个 CSV 文件,并允许用户在 API 被命中时下载它。这是我想象中的用户交互
User hit a button ->
jquery do $.get to api ->
api endpoint prepares data ->
api endpoint pass in data to another function to generate csv
这是我目前的代码
public function test(){
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies;
$f = fopen("php://output", "w");
$test_data = array(
array(
'something1' => '2'
),
array(
'somethign2' => '3'
),
);
foreach($test_data as $line){
fputcsv($f, $line, ',');
}
fclose($f);
}
我发现浏览器并没有下载 csv,而是简单地呈现结果的内容
2
3
当我使用 Chrome 在网络中查看时。
我尝试将内容类型更改为强制下载,但结果仍然相同
任何帮助将不胜感激。
谢谢
【问题讨论】:
-
如果将
file.csv括在引号中会怎样?像这样:header("Content-Disposition: attachment; filename=\"file.csv\"");