在codeigniter中下载CSV

时间:2018-03-19 11:14:13

标签: php codeigniter

    $ci =& get_instance();
    $ci->load->dbutil();
    $result =  $ci->dbutil->csv_from_result($data);
    $filename = "sample.csv";
    $fp = fopen('php://output', 'w');
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename='.$filename.'";'); 
    header('Cache-Control: must-revalidate,post-check=0, pre-check=0');
    header("Pragma: no-cache");
    header("Expires: 0");
    foreach ($final_res as $line){ 
        fputcsv($fp,explode(',',$line)); 
    }         
    fclose($fp);          
    exit;

我无法下载CSV文件。我找不到任何错误。请帮忙

2 个答案:

答案 0 :(得分:0)

尝试更改代码中的标题。

header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));

答案 1 :(得分:0)

为什么不使用CI的force_download()辅助函数。 LINK