PHP fputcsv() Function

Definition and Usage

The fputcsv() function formats a line as CSV and writes it to an open file.

The function returns the length of the written string. If an error occurs, it returns false.

Syntax

fputcsv(file,fields,seperator,enclosure)
Parameters Description
file Required. Specifies the open file to be written to.
fields Required. Specifies the array from which data is to be obtained.
seperator Optional. Specifies the character used to separate fields. The default is the comma (,).
enclosure Optional. Specifies the character used to enclose fields. The default is the double quote ".

Description

fputcsv() formats a line (using fields An array passed in) is formatted as CSV and written to file Specified file.

Tips and Comments

Tip:See fgetcsv() function.

Example

<?php
$list = array
(
"George,John,Thomas,USA",
"James,Adrew,Martin,USA",
);
$file = fopen("contacts.csv","w");
foreach ($list as $line)
  {
  fputcsv($file,split(',',$line));
  }
fclose($file);
?>

After the above code is executed, the CSV file will be similar to this:

George,John,Thomas,USA
James,Adrew,Martin,USA