Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...