Last updated on January 5th, 2020 at 07:01 pm

In this post I will explain to you how we can create a CSV (comma-separated value) file using simple PHP code. CSV file is very useful when we need to import and export data from the server or transfer data to other servers or in excel format. If you want to export data in excel you can read this post:- Import & Export data to Excel from MySQL using PHP.

Prerequisites

Before we start creating CSV with PHP, I hope you have a good basic knowledge of PHP.

Steps to create CSV with PHP

Step 1. Create a new PHP file in server.

Step 2. Now we need sample data to put in CSV file you can load data from a database or you can create a static array which contains sample data.

<?php
$data = array( 
  array("data1", "data2", "data3"), 
  array("data4", "data5", "data6"), 
  array("data7", "data8", "data9") 
);

Step 3.  Now put that sample data in temp file using the below code.

<?php
$data = array( 
    array("data", "data", "data"),
    array("data", "data", "data"), 
    array("data", "data", "data") 
); 
$file = fopen('php://output', 'w'); 
fputcsv($file, array('label1', 'label2', 'label3'));
 
while ($data as $row) { 
    fputcsv($file, $row); 
}

Step 4. Now we need force browser to download CSV file using PHP Headers

<?php
header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=file.csv"); 
header("Pragma: no-cache"); 
header("Expires: 0");

Here is complete code to create a CSV file using PHP

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$data = array(
    array("data", "data", "data"),
    array("data", "data", "data"),
    array("data", "data", "data")
);   
$file = fopen('php://output', 'w');                              
fputcsv($file, array('label1', 'label2', 'label3'));
while ($data as $row) {
   fputcsv($file, $row);
}

Hope this code help you.