CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

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)

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();
	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){ 

Crud_model.php (Model)

class Crud_model extends CI_Model 
	function getUserDetails(){
 		$response = array();
		$q = $this->db->get('users');
		$response = $q->result_array();
	 	return $response;

users_view.php (View)

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

   <!-- User Records --> 
   <table border='1' style='border-collapse: collapse;'> 
     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>"; 

Run the program on your browser with URL:


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