【发布时间】:2021-04-20 00:09:55
【问题描述】:
背景: 我在网站上有一个表格,用户可以从中选择行,然后单击导出按钮下载这些行的 .csv。
我正在从前端的表中创建一个数组数组,并通过 AJAX 将该数组传递给一个 PHP 脚本,该脚本使用 fputcsv() 将它们放入 .csv 格式。我能够回显结果,并将结果推送到服务器上的 .csv 文件,并且都可以正确显示。但无论出于何种原因,我都无法让浏览器提供文件供下载。
我参考了很多 stackoverflow 文章,并对 HTTP 标头进行了研究,但似乎没有任何效果。
我的代码贴在下面:
<?php
// this is the array of arrays passed via AJAX
$gaps = $_POST["gaps"];
function array_to_csv_download($array, $filename='export.csv', $delimiter=",") {
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
array_to_csv_download($gaps, 'gaps.csv');
【问题讨论】:
-
将标题从“Content-type: text/csv”更改为“Content-type: binary/octet-stream”
-
你的代码对我来说很好,没有 $gaps 变量,所以如果你错过了什么,请检查那里
标签: php