What is the fputcsv() function in PHP?

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).

Syntax

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

Parameters

$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.

Return value

On success, the function returns the length of the written string. Otherwise, the function returns False.

Code

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 array
foreach ($cities as $line)
{
// the second parameter should be an array
// putting each array in the file converting it into csv
fputcsv($myfile, $line);
}
// close the file
fclose($myfile);
?>
Copyright ©2024 Educative, Inc. All rights reserved