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:
<?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;
}
}
<?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;
}
}
<!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.