Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

php - Download csv from codeigniter mysql

I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.

Here's my code:

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

?>

$stories is my array created from the MySQL query.

Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?


final working code:

 $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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can call model CSV() from your controller as

$this->load->model('Users_model');
$this->Users_model->csv();

and in the model

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

Your File will start downloading


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...