How to create csv file with php? Generating csv file with php and download it.

In this article we will discuss about how to create CSV file with php. Rather than creating csv file we will also download the same. This is achieved by the help of fputcsv() function. It formats a line as csv and also writes to an open file.

If you are looking for export excel in codeigniter click here.

PHP

<?php
     $con = mysqli_connect("localhost","root","","registration");
     header('Content-Type: text/csv; charset=utf-8');  
     header('Content-Disposition: attachment; filename=filename.csv');  
     $output = fopen("php://output", "w");  
     fputcsv($output, array('id', 'name', 'age'));  

     $sql = "select * from employees";
     $result = mysqli_query($con,$sql);
     while($row = $result->fetch_assoc())
     {
	 fputcsv($output, $res); 
     } 
     fclose($output);
?>
  1. Connect with database
  2. Send header content type as text/csv with attachment filename.csv
  3. Open file with write permission
  4. Pass the $output and array() values to file to set the header elements
  5. Get data from table
  6. Inside while loop pass the output and each row to fputcsv()
  7. Close the file

Leave A Comment