【问题标题】:Downloading a file in csv php在csv php中下载文件
【发布时间】:2012-10-22 06:12:05
【问题描述】:

我已经编写了一个函数来下载 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;
}

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

【问题讨论】:

    标签: php csv download moodle


    【解决方案1】:

    像这样试试..

    header('Content-Type: application/csv');
    header('Pragma: no-cache');
    

    【讨论】:

    • 没有。仍然可以在浏览器中获取所有内容。
    【解决方案2】:

    以下标题应强制下载

    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");
    

    【讨论】:

    • 没有。没有强制下载。仍然可以在浏览器中获取所有内容。
    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多