How to Create a CSV File in PHP

Contents
In this article, you will learn how to create a CSV file in PHP.
PHP fputcsv() Function
The fputcsv() function formats a line as CSV and writes it to an open file.
Syntax
fputscsv($file, $fields, $separator, $enclosure, $escape)
Parameter Values
The first argument $file specifies the output result of the fopen function.
$file= fopen("Path of output CSV file", "w");
The second argument $fields specifies the array to be written.
The third argument $separator specifies the delimiter.
If omitted, ,
is used.
The fourth argument $enclosure specifies the enclosing character.
If omitted, "
is used.
However, the specification is such that the enclosing character is added only when the character string to be output contains a single-byte space.
The fifth argument, $escape, specifies a special character to be recognized as a character.
Sample
In the example below, we write a pre-set string to an array to sample.csv.
// Define multiple arrays to write to the CSV file
$ary = array(
array("PCODE", "PNAME", "PRICE($)"),
array("001", "Apple", "1"),
array("002", "Orange", "2"),
array("003", "Banana", "3"),
);
// Open a file
$file = fopen("sample.csv", "w");
// If the file can be opened normally, write it
if ($file) {
// Calls and writes arrays in order from $ary
foreach($ary as $line){
// Write to a file with the fputcsv function
fputcsv($file, $line);
}
}
// Close the file
fclose($file);
First, define an array $ary which will be the data to write to the CSV file.
Next, open (create) sample.csv to write data, and if sample.csv can be opened normally, retrieve arrays in order from $ary and write each line to sample.csv increase.
The resulting output will be:
PCODE,PNAME,PRICE($)
001,Apple,1
002,Orange,2
003,Banana,3