从codeigniter mysql下载csv

End*_*ave 2 php mysql csv codeigniter

我想我错过了一些明显的东西.我正在尝试将数据集从MySQL查询导出到CSV而不将其打印到浏览器.

这是我的代码:

<?php

$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);

?>
Run Code Online (Sandbox Code Playgroud)

$stories 是我从MySQL查询创建的数组.

目前一切都打印到浏览器没有错误,没有下载,但我想强制CSV下载.我怎样才能做到这一点?


最终工作代码:

 $this->load->helper('download');

    $list = $stories;
    $fp = fopen('php://output', 'w');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
        }

    $data = file_get_contents('php://output'); 
    $name = 'data.csv';

    // Build the headers to push out the file properly.
    header('Pragma: public');     // required
    header('Expires: 0');         // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    exit();

    force_download($name, $data);
    fclose($fp);
Run Code Online (Sandbox Code Playgroud)

Har*_*esh 13

您可以CSV()从控制器调用模型

$this->load->model('Users_model');
$this->Users_model->csv();
Run Code Online (Sandbox Code Playgroud)

在模型中

function csv()
{
        $this->load->dbutil();
        $this->load->helper('file');
        $this->load->helper('download');
        $query = $this->db->query("SELECT * FROM Users");
        $delimiter = ",";
        $newline = "\r\n";
        $data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
        force_download('CSV_Report.csv', $data);
}
Run Code Online (Sandbox Code Playgroud)

您的文件将开始下载


小智 5

我不知道从 Codeigniterforce_download()函数集中设置了哪些标头。如果它确实进入屏幕,我会怀疑缺少必要的标题。您可以将以下标题添加到您的代码中以设置正确的 csv 下载标题(缓存控件将确保每次下载新数据:

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