使用PHP和jQuery生成并下载.csv文件 [英] generate and download a .csv file with PHP and jQuery
本文介绍了使用PHP和jQuery生成并下载.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成一个.csv文件,然后使用AJAX下载
I want to generate a .csv file then download it with AJAX
现场csv.php,我有以下代码:
Insite csv.php I have this code:
<?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);
}
?>
因此,当我转到csv.php时,它使我可以下载csv文件.
so when I'm going to csv.php it makes me download the csv file.
然后在test.php内部,我有以下jQuery代码:
Then inside test.php I have this jQuery code:
$(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));
}
});
});
但是当我单击#listCSV时,什么也没发生,什么也没有下载
But when I'm clicking on #listCSV nothing happens, nothing is being downloaded
您知道如何在单击#listCSV时如何下载csv文件吗?
Any idea how can I download the csv file when clicking on #listCSV?
推荐答案
您需要更改标题信息以将其输出为下载文件:
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;
这篇关于使用PHP和jQuery生成并下载.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文