How to Write Data to CSV File in PHP Example

Sovary October 13, 2022 500
1 minute read

We will discuss about how to create a csv file in raw php. You will learn how to implement in php how to write CSV file and export. Example below we will generate CSV file from array php by follow steps to convert associative array to CSV file in PHP.

This article will show you example of create and write array into CSV file by using PHP, we will use fopen() function to open file then use fputcsv() function to write format as CSV.

So let's see example below

Create file index.php

<?php 
   header('Content-Type: text/csv');
   header('Content-Disposition: attachment; filename="employee.csv"');
   
   $head = ["id","name","email","gender"];
   $employees = [
      [ "id" => 1, "name" => "Sovary", "email" => "example1@gmail.com", "gender" => "male"],
      [ "id" => 2, "name" => "Sok Sao", "email" => "example2@gmail.com", "gender" => "male"],
      [ "id" => 3, "name" => "Lina", "email" => "example3@gmail.com", "gender" => "female"],
      [ "id" => 4, "name" => "Nika", "email" => "example4@gmail.com", "gender" => "female"]
   ];
   // open for write file
   $path = fopen('php://output', 'wb');
   fputcsv($path , $head);
   foreach($employees as $emp) 
   {
      // write array data
      fputcsv($path , $emp);
   }

   // close file
   fclose($path );
   
?>

Output:

PHP write CSV example in excel

This sample example you can apply in Laravel as well in your controller file or in pure example. Have a nice day!

You might also like...

 

PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him