PHP MVC CodeIgniter Laravel Core PHP MORE

How to export record in excel or CSV file using PHP MVC with example


In this example we using Models, Views, Controller Structure for to export record in excel or CSV in PHP MVC.

To export record in excel or CSV first we have to create a Controller file.

controller/hello.php

index.php

<?php
class Hello extends Controller {
	function __construct() {
		parent::__construct();
		
	}
	function view() {
         $this->view->content = $this->model->get_records();
         $this->view->render('hello/view');
    }
	function export(){
			$filename = 'users_'.date('Ymd').'.csv'; 
			header("Content-Description: File Transfer"); 
			header("Content-Disposition: attachment; filename=$filename"); 
			header("Content-Type: application/csv; ");
			$usersData = $this->model->get_records();
			
			$file = fopen('php://output','w');
			$header = array("Sl.no","Name","Email","Contact"); 
			fputcsv($file, $header);
			foreach ($usersData as $key=>$line){ 
				fputcsv($file,$line); 
			}
			fclose($file); 
			exit; 
	}
}
  

Here is the model file which we are using for inserting data to database.

The file index_model.php is created under Models folder

models/hello_Model.php

index_model.php

<?php
class Hello_Model extends Model
{
	public function __construct()
	{
		parent::__construct();
	}
	public function get_records()
    {
       return $this->db->select("SELECT * FROM `user_data` ORDER BY id DESC");
    }
}	

Here is the view file view.php which inside views folder contains the form.

views/hello/view.php

<!DOCTYPE html>
<html>
<body>
<table border="2" id="internalActivities" style="width:100%" class="table table-bordered">
<a href="<?php echo URL; ?>hello/export">Export</a>
<tbody>
	<tr>
		<th>Sl No</th>
		<th>Name</th>
		<th>Email</th>
		<th>Contact</th>
		<th>Action</th>
		<th>Action</th>
	</tr>
	<?php
	foreach($this->content as $row){
		?>
	<tr>
		<td><?php echo $row['id']; ?></td>
		<td><?php echo $row['name']; ?></td>
		<td><?php echo $row['email']; ?></td>
		<td><?php echo $row['contact']; ?></td>
		<td><a href="delete?id=<?php echo $row['id']; ?>">Delete</a></td>
		<td><a href="update?id=<?php echo $row['id']; ?>">Update</a></td>
	</tr>
	<?php
	}
	?>
</tbody>
</table>
</html>
</body>
Path: localhost/project_folder_name/view_folder_name/view_filename
Example: localhost/mvc/hello/view