使用PHP和jQuery生成并下载一个.csv文件


generate and download a .csv file with PHP and jQuery

我想生成一个。csv文件,然后用AJAX下载

在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);
}
?>

所以当我进入csv。php时它会让我下载csv文件

然后在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));
            }
        });
    }); 

但是当我点击#listCSV时什么也没发生,没有东西被下载

任何想法我怎么能下载csv文件时,点击#listCSV?

  1. 生成csv文件并保存在一个目录中。说:根/csv/file_timestamp.csv
  2. 当文件生成时,只需使用您链接上的file_timestamp.csv位置。如果file_timestamp。csv可以通过

    访问

    http://project/csv/file_timestamp.csv

然后直接链接到常规链接:

<a href="http://project/csv/file_timestamp.csv"/>download csv</a>

注意:如果您不希望多个用户生成CSV文件,那么只需创建一个临时文件,然后您可以将链接设置为静态。如果不行,每隔3分钟删除CSV文件夹中的所有文件

您需要更改标题信息以输出为下载:

        $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;