How to Write Data to CSV File in PHP Example

Sovary October 13, 2022 514
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him