0

我编写了一个函数来下载 php 中 csv 格式的文件,如下所示:-

function report_download_csv($fields, $data, $filename) {
        global $CFG;
require_once($CFG->dirroot.'/user/profile/lib.php');

    $filename = clean_filename($filename.'-'.date('Y-m-d').'.csv');
    header("Content-Type: application/download\n");
    header("Content-Disposition: attachment; filename=$filename");
    header("Expires: 0");
    header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
    header("Pragma: public");

    $row = array(); 
        $date_field = array('registrationdate', 'expirydate', 'startdate', 'enddate');
        $totalrow = count($fields);
        $row[] = implode(',',$fields)."\n";

        foreach($data as $d){
            for($i=0;$i<$totalrow;$i++){
                    $row_d[] = $d->$fields[$i];
            }
            $row[] = implode(',',$row_d);
            $row_d = array();
        }
        echo implode($row, "\n");
    die;
}

但是,当我调用该函数时,它只是在浏览器中打印结果。有什么我应该改变的功能吗?

4

2 回答 2

1

试试这样。。

header('Content-Type: application/csv');
header('Pragma: no-cache');
于 2012-10-22T06:18:12.890 回答
0

以下标题应强制下载

header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");
于 2012-10-22T06:16:57.260 回答