How to create a CSV file using PHP?

In this article, we are going to learn about how to create a CSV file using PHP.

Before getting into the topic, first of all, let me explain, what is a CSV file? and how it plays a vital role in data manipulation.

What is a CSV file?




CSV(Comma Separate Values) is a text file that uses comma to separate values. This is used to export data easily and also used to import data from it in an efficient manner.

It stores tabular data where each comma separates the column i.e. shows the end of that particular column. The next line containing another set of values form a new row.

Example:

Consider a table that stores the Roll no. , Name and Mark of 3 students:

Roll
Name
Mark
1
John
38
2
Sid
72
3
Jk
20

 

The above table data may be represented in CSV format as follows:

Roll,Name,Mark
1,John,38
2,Sid,72
3,Jk,20

Using fputcsv() for creating CSV file in PHP

To create CSV file in PHP,following function is used:

fputcsv($file,$fields,$separator,$enclosure);

Here,

  • $file : It specifies the file name.
  • $fields : It specifies array of data to be inserted.
  • $separator : It specifies the field separator (By default it is comma i.e “,”).
  • $enclosure :¬†It specifies the field enclosure character.

Note:

First two arguments are compulsory whereas last two arguments are optional.

Creating CSV file using static data

The following code illustrates the use of fputcsv():

<?php
//creating a mycsv.csv file
$cfile = fopen('mycsv.csv', 'w');
 
//Inserting the table headers
$header_data=array('Roll','Name','Mark');

fputcsv($file,$header_data);
 
//Data to be inserted
$fdata = array(
array('1','John','38'),
array('2','Sid','72'),
array('3','Jk','20')
);
 
// save each row of the data
foreach ($fdata as $row)
{
fputcsv($cfile, $row);
}
 
// Closing the file
fclose($cfile);
?>

Output:

Roll
Name
Mark
1
John
38
2
Sid
72
3
Jk
20

 

From the above article, we learnt the use of putcsv() function and writing the data by creating a CSV file in PHP.

You may also read,

If you have any doubt on this topic, put a comment below:


Leave a Reply

Your email address will not be published. Required fields are marked *