[英]generate and download a .csv file with PHP and jQuery
I want to generate a .csv file then download it with AJAX 我想生成一个.csv文件,然后用AJAX下载它
Insite csv.php I have this code: Insite csv.php我有这个代码:
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("th.csv","r");
$list = array();
while(! feof($file))
{
$list[] = (fgetcsv($file));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
$list = array_filter($list);
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
?>
so when I'm going to csv.php it makes me download the csv file. 所以当我要去csv.php时它会让我下载csv文件。
Then inside test.php I have this jQuery code: 然后在test.php里面我有这个jQuery代码:
$(document).on('click', '#listCSV', function() {
var el = $(this),
csv = el.attr('csv');
$.ajax({
type: 'POST',
url: 'csv.php',
data: {
listCSV: csv
},
success: function(data, textStatus, jqXHR) {
el.html($(data));
}
});
});
But when I'm clicking on #listCSV nothing happens, nothing is being downloaded 但当我点击#listCSV时没有任何反应,没有任何内容被下载
Any idea how can I download the csv file when clicking on #listCSV? 知道如何在点击#listCSV时下载csv文件吗?
when the file is generated just use the file_timestamp.csv location on you're link. 生成文件时,只需在链接上使用file_timestamp.csv位置。 so if your file_timestamp.csv is can be accessed via
所以如果你的file_timestamp.csv可以通过访问
http://project/csv/file_timestamp.csv
then just link it to a regular link: 然后只需将其链接到常规链接:
<a href="http://project/csv/file_timestamp.csv"/>download csv</a>
Note: if you're not expecting multiple users to generate csv files then just make a temporary file then you can set the link as static. 注意:如果您不希望多个用户生成csv文件,那么只需创建一个临时文件,然后您可以将链接设置为静态。 if not just delete every file in the csv folder every 3mins
如果不是每3分钟删除csv文件夹中的每个文件
You need to change header information to output it as download : 您需要更改标题信息以将其输出为下载:
$out = fopen("php://output", 'w');
$emails = array();
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="'.$this->filename.'.csv"');
foreach($contacts as $adr) $emails[] = $adr->getEmail();
fputcsv($out, $emails);
fclose($out);
exit;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.