Codeigniter – Create, export, and download a CSV File from a Model.
If you need to export as a CSV file a model that you already have in your database, you can do the following in your code:
- Add a method exportCSV in your Controller: application/controller/MyController.php
123456789101112131415161718192021222324252627282930313233Class MyController extends CI_Controller {public function __construct() {parent::__construct();// Load database$this->load->model('MyModel');}public function exportCSV(){// get data$myData = $this->MyModel->getData();// file name$filename = 'mydata_'.date('Ymd').'.csv';header("Content-Description: File Transfer");header("Content-Disposition: attachment; filename=$filename");header("Content-Type: application/csv; ");// file creation$file = fopen('php://output', 'w');$header = array("Column 1","Column 2","Column 3","Column 4");fputcsv($file, $header);foreach ($myData as $line){fputcsv($file,array($line->field1,$line->field2,$line->field3,$line->field4));}fclose($file);exit;}} - In the preferred view, add the following export link:
1<a href='<?= base_url() ?>/myController/exportCSV'>Export</a>