PHP fputcsv() Function

Definition and Usage

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

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

Syntax

fputcsv(file,fields,seperator,enclosure)
Parameters Description
file Required. Specifies the open file to write to.
fields Required. Specifies the array from which to obtain data.
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 Array passed) formatted as CSV and written by file The 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