CodeIgniter Laravel PHP Example Javascript jQuery MORE
Need a Website Or Web Application Or Any Help.Contact Us: +91 9437911966 (Whatsapp) Note: Paid Service
Students Tutorial app relased. Download Now.

How to export record in excel or CSV file using CodeIgniter framework PHP


In this example we are going to show you how to how to export record in excel or CSV file using CodeIgniter framework PHP.

Here we using 3 files for import data in CodeIgniter framework MySQL PHP:

  • Crud.php Path: codeIgniter\application\controllers\Crud.php
  • Crud_model.php Path: codeIgniter\application\models\Crud_model.php
  • users_view.php Path: codeIgniter\application\views\users_view.php

Crud.php (Controller)

<?php
class Crud extends CI_Controller 
{
	public function __construct()
	{
		parent::__construct();//call CodeIgniter's default Constructor
		$this->load->database();//load database libray manually
		$this->load->model('Crud_model');//load Model
	}
	public function index(){
		$data['usersData'] = $this->Crud_model->getUserDetails();
		$this->load->view('users_view',$data); 
	}
	public function export_csv(){ 
		// file name 
		$filename = 'users_'.date('Ymd').'.csv'; 
		header("Content-Description: File Transfer"); 
		header("Content-Disposition: attachment; filename=$filename"); 
		header("Content-Type: application/csv; ");
	   // get data 
		$usersData = $this->Crud_model->getUserDetails();
		// file creation 
		$file = fopen('php://output','w');
		$header = array("Username","Name","Gender","Email"); 
		fputcsv($file, $header);
		foreach ($usersData as $key=>$line){ 
			fputcsv($file,$line); 
		}
		fclose($file); 
		exit; 
	}
}

Crud_model.php (Model)

<?php
class Crud_model extends CI_Model 
{
	function getUserDetails(){
 		$response = array();
		$this->db->select('username,name,gender,email');
		$q = $this->db->get('users');
		$response = $q->result_array();
	 	return $response;
	}
	
}

users_view.php (View)

<!DOCTYPE html>
<html lang="en">
 <head> 
   <meta charset="utf-8"> 
   <title> CodeIgniter EXPORT</title>
 </head>
 <body>
   <!-- Export Data --> 
   <a href='<?= base_url() ?>crud/export_csv'>Export</a><br><br>

   <!-- User Records --> 
   <table border='1' style='border-collapse: collapse;'> 
     <thead> 
      <tr> 
       <th>Username</th> 
       <th>Name</th> 
       <th>Gender</th> 
       <th>Email</th> 
      </tr> 
     </thead> 
     <tbody> 
     <?php
     foreach($usersData as $key=>$val){ 
       echo "<tr>"; 
       echo "<td>".$val['username']."</td>"; 
       echo "<td>".$val['name']."</td>"; 
       echo "<td>".$val['gender']."</td>"; 
       echo "<td>".$val['email']."</td>"; 
       echo "</tr>"; 
      } 
      ?> 
     </tbody> 
    </table>
  </body>
</html>

Run the program on your browser with URL:

http://localhost/codeIgniter/index.php/Crud

Here codeIgniter is my folder name. Put your folder name instead of codeIgniter.Rest of things are same.