The fputcsv()
function in PHP is a built-in function in PHP. This method is useful for formatting any line of string as a .csv
format (comma-separated values).
fputcsv ( $file, $fields, $separator, $enclosure )
$file
: The .csv
file for writing values.
$fields
: Arrays containing the lines of data to be formatted into .csv
.
$separator
: Separator that is used in the new file. We use ,
(comma) by default.
$enclosure
: This is an optional parameter specifying the enclosure character of a field.
On success, the function returns the length of the written string. Otherwise, the function returns False
.
Let’s look at a coding example to understand how the fputcsv()
method works.
<?php// array of cities$cities = array(array("California", "Boston", "Chicago", "New York"),array("Amsterdam", "London", "Madrid", "Paris"),array("Islamabad", "Mumbai", "Karachi", "Dubai"));// opening the file "file.csv" for writing the values in it$myfile = fopen("file.csv", "w");// putting each line in the file.// iterating through each individual arrayforeach ($cities as $line){// the second parameter should be an array// putting each array in the file converting it into csvfputcsv($myfile, $line);}// close the filefclose($myfile);?>