Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

fputcsv

Writes an array to a file as a CSV line.

Syntax

fputcsv(resource $stream, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n"): int|false

Parameters

ParameterTypeDescription
$streamresourceA handle to an opened file.
$fieldsarrayThe field values.
$separatorstringOptional. The field separator.
$enclosurestringOptional. The quote character.
$escapestringThe escape character; pass an empty string.
$eolstringOptional. The line ending.

Return value

int|falseThe length of the written line, or `false`.

Examples

Exporting a table to CSV:

<?php
 
$file = sys_get_temp_dir() . '/ref-write.csv';
$rows = [['name', 'price'], ['Tea', 250], ['Coffee, black', 400]];
 
$handle = fopen($file, 'w');
 
foreach ($rows as $row) {
    fputcsv($handle, $row, ',', '"', '');
}
 
fclose($handle);
 
echo file_get_contents($file);

Output:

name,price
Tea,250
"Coffee, black",400

Notes

The function quotes a value containing a comma by itself. For Excel to open non-ASCII text correctly, the mark "\xEF\xBB\xBF" is written at the start of the file.

See also

  • fgetcsv — Reads a line of a CSV file and splits it into fields.
  • fopen — Opens a file for reading or writing piece by piece.
  • implode — Joins array elements into a string.

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.