Showing posts with label Codeigniter. Show all posts
Showing posts with label Codeigniter. Show all posts

Tuesday, 22 July 2014

Create CSV file and download using Codeigniter

The 'dbutil' class of codeigniter is used for creating csv file, so you need to load this class first,

$this->load->dbutil();

In this example we going to create a csv file from database table. Please check out the code snippet below.

public function createCsvDownload()
 {
  $this->load->dbutil();
  $query = $this->db->query("SELECT * FROM table_name"); 
  $delimiter = ",";
  $newline = "\r\n";
  $data= $this->dbutil->csv_from_result($query, $delimiter, $newline);
  
  header('Content-Description: File Transfer');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename=csv_file.csv');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Transfer-encoding: binary');
  
  echo $data;
  
  flush();
  exit;  
 }