在一个脚本中创建和下载CSV文件

时间:2014-11-08 17:15:01

标签: php http-headers download

我想在一个脚本中创建和下载CSV文件。

到目前为止,我一直在通过使用cron作业预先创建文件来避免我的知识缺乏 通过链接下载文件。

我有这个:

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die ('Error connecting to mysql');

$get_members_csv_query = "SELECT * FROM members";
$get_members_csv_result=$conn->query($get_members_csv_query, MYSQLI_STORE_RESULT);

$all_members_array = array();

while ($get_members_csv_array = $get_members_csv_result->fetch_assoc())
{
    array_push($all_members_array, $get_members_csv_array);
}


$file = fopen('members.csv', 'w');                              
  fputcsv($file, array('email', 'First Name', 'Surname', 'Gender','DOB','Registered On','Country','paid','Children','Wants Kids','Relationship','Body Type','Height','Smoke','Drink','Phone','Region','Religion','Community'));      
  foreach ($all_members_array as $row) {
        fputcsv($file, $row);              
  }


      exit(); 

这会成功创建文件,但是我需要添加到脚本中以使其在创建后自动下载CSV文件?

如果脚本:

,我已尝试将其放在开头
header("Content-type: text/csv");
  header("Content-Disposition: attachment; filename=members.csv");
  header("Pragma: no-cache");
  header("Expires: 0");

但它会在脚本完成(甚至开始)创建文件之前下载文件。

我尝试将标题放在脚本的末尾,并在顶部使用ob_start() - 结果相同。

由于

2 个答案:

答案 0 :(得分:0)

您永远不会将文件内容发送到浏览器。它应该是:

$file = fopen('members.csv', 'w');                              
fputcsv($file, array('email', 'First Name', 'Surname', 'Gender','DOB','Registered On','Country','paid','Children','Wants Kids','Relationship','Body Type','Height','Smoke','Drink','Phone','Region','Religion','Community'));      
foreach ($all_members_array as $row) {
    fputcsv($file, $row);              
}
fclose($file);

// Download file
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=members.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('members.csv');

exit();

答案 1 :(得分:0)

试试这个: 从exit()行,修改为:

exit(dnl("members.csv"));//call dnl function

然后在同一页面上写下dnl函数:

function dnl($fn){
 // Send Header
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");;
    header("Content-Disposition: attachment;filename=$fn"); 
    header("Content-Transfer-Encoding: binary ");
}

请记住内容类型" application / octet-stream"可以像以前一样更改为仅匹配csv。