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 written string. 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 that separates fields. The default is a comma (,).
enclosure Optional. Specifies the character that surrounds 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 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