The fputcsv Function

The fputcsv function formats the passed array into a CSV string and writes it to the specified file. The first parameter is a file pointer, the second is an array of data to write. The third parameter can specify the field delimiter (comma by default), the fourth - the string enclosure (double quotes by default).

Syntax

phpfputcsv(
  resource $handle,
  array $fields,
  string $delimiter = ",",
  string $enclosure = '"',
  string $escape_char = "\"
);

Example

Let's write an array to a CSV file:

php<?php
  $file = fopen('data.csv', 'w');
  $data = ['a', 'b', 'c', 'd', 'e'];
  fputcsv($file, $data);
  fclose($file);
?>

Contents of the file data.csv:

php"a","b","c","d","e"

Example

Let's write several lines to a CSV file using a semicolon as a delimiter:

php<?php
  $file = fopen('data.csv', 'w');
  $data1 = [1, 2, 3, 4, 5];
  $data2 = ['x', 'y', 'z'];
  fputcsv($file, $data1, ';');
  fputcsv($file, $data2, ';');
  fclose($file);
?>

Contents of the file data.csv:

php"1";"2";"3";"4";"5"
"x";"y";"z"

Example

Let's write an array with data containing commas:

php<?php
  $file = fopen('data.csv', 'w');
  $data = ['John, Doe', 'johndoe@example.com', 'New York'];
  fputcsv($file, $data);
  fclose($file);
?>

Contents of the file data.csv:

php"John, Doe","johndoe@example.com","New York"

See Also

  • the fgetcsv function,
    which reads data from CSV
  • the fwrite function,
    which writes to a file
  • the fopen function,
    which opens a file