306 of 410 menu

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

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

Example

Let's write an array to a CSV file:

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

Contents of the file data.csv:

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

Example

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

<?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:

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

Example

Let's write an array with data containing commas:

<?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:

"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
byenru