使用 PHP 下载 CSV 文件
Downloading CSV file with PHP
我正在尝试使用 PHP 下载 CSV 文件,但我无法获取对话框。
我已经更改了 headers 并使用了 readfile() 函数,如图所示 here
这是我的代码:
$nodeId = 'something';
$filename = "/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/$nodeId.csv";
header('Content-type: text/csv');
header('Content-disposition: attachment; filename ="report.csv"');
readfile($filename);
** 编辑 **
也按照建议尝试了这个:
header('Content-Disposition: attachment; filename="report.csv"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('report.csv'));
当我检查 Firebug 中的响应时,我可以看到返回的整个 CSV 文件。另外 headers 变为:
Content-Type text/csv
Content-disposition attachment; filename ="report.csv"
所以我不明白为什么我没有得到保存文件的对话框。
添加这些 headers:
header('Content-Disposition: inline; filename="report.csv"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
毕竟我没有使用上面的方法,我这样做了,效果很好,而且更直接:
var ajaxurl = 'exportNodeData.php', // script to run
data = {nodeId:nodeId}; // data to pass
$.post(ajaxurl, data, function (response) {
document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';
});
这是 ajax 请求,我执行该请求是为了创建 CSV 文件(也是压缩文件)。然后我使用这一行:
document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';
为了强制下载文件。
我正在尝试使用 PHP 下载 CSV 文件,但我无法获取对话框。 我已经更改了 headers 并使用了 readfile() 函数,如图所示 here
这是我的代码:
$nodeId = 'something';
$filename = "/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/$nodeId.csv";
header('Content-type: text/csv');
header('Content-disposition: attachment; filename ="report.csv"');
readfile($filename);
** 编辑 **
也按照建议尝试了这个:
header('Content-Disposition: attachment; filename="report.csv"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('report.csv'));
当我检查 Firebug 中的响应时,我可以看到返回的整个 CSV 文件。另外 headers 变为:
Content-Type text/csv
Content-disposition attachment; filename ="report.csv"
所以我不明白为什么我没有得到保存文件的对话框。
添加这些 headers:
header('Content-Disposition: inline; filename="report.csv"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
毕竟我没有使用上面的方法,我这样做了,效果很好,而且更直接:
var ajaxurl = 'exportNodeData.php', // script to run
data = {nodeId:nodeId}; // data to pass
$.post(ajaxurl, data, function (response) {
document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';
});
这是 ajax 请求,我执行该请求是为了创建 CSV 文件(也是压缩文件)。然后我使用这一行:
document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';
为了强制下载文件。