Codeigniter and generating CSV files Codeigniter and generating CSV files codeigniter codeigniter

Codeigniter and generating CSV files


I've adoped a fairly simple solution based on the 3rd solution in the question "Download csv from codeigniter mysql", which is to have a model function:

function csv($query, $filename = 'CSV_Report.csv'){        $this->load->dbutil();        $this->load->helper('file');        $this->load->helper('download');        $delimiter = ",";        $newline = "\r\n";        $data = $this->dbutil->csv_from_result($query, $delimiter, $newline);        force_download($filename, $data);}

In the controller where you generate the query, add a $csv boolean parameter, eg:

function membercountry($country_id = NULL, $csv = false)

and have a condition in the controller function which will call the model function if $csv is true or 1:

    if ($csv)    {        $date = date('dmy');        $csvfile = "membercountry" . $date . ".csv";        $this -> Queries_model -> csv($data['membercountries_query'], $csvfile);    }

Then in the query result view, after displaying the results in human-readable form in the browser, present a hyperlink:

<a href="queries/membercountry/<?=$country_id?>/1">Download result as CSV</a>

When clicked, it re-calls the controller with $csv as true which then invokes the model function csv().

This is a fairly general solution for my application, which only needs a few extra lines in a controller function, and saves writing a CSV file to server or having a specific view with detailed and complex headers. It's not the solution, just a fairly simple quick-and-dirty solution which CI developers on here might find useful. Once again, a big thanks to the CI community for creating the dbutils class which makes outputting CSV a doddle.

Edit: it might be tidier from a MVC viewpoint to put the csv() function in the controller rather than the model, and call it by $this -> csv().


Blockquote In the Model

$this->load->dbutil();$q=$this->db->query("select * from student order by idate desc");$delimiter = ",";$newline = "\r\n";return $this->dbutil->csv_from_result($q,$delimiter,$newline);

In The Controller

$this->load->helper('download');$this->load->model('mdl');$row  = $this->mdl->getall();$name = 'mycsv.csv';force_download($name,$row);


you just need to to is download csv helper file for codeigniter and run you script like it

 $this->db->select('*')->from('*');  $query = $this->db->get('your_table');$this->load->helper('csv');query_to_csv($query, TRUE, 'filename.csv');