fputcsv()

fputcsv() — Format line as CSV and write to file pointer.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.1.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

fputcsv() formats a line (passed as a fields array) as CSV and writes it (terminated by a eol) to the specified stream.

Signature

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

Parameters

ParameterTypeWhat it takes
$streamresourceThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
$fieldsarrayAn array of strings.
$separatorstringThe separator parameter sets the field separator. It must be a single byte character.
$enclosurestringThe enclosure parameter sets the field enclosure character. It must be a single byte character.
$escapestringThe escape parameter sets the escape character. It must be a single byte character or the empty string. The empty string ("") disables the proprietary escape mechanism.
$eolstringThe optional eol parameter sets a custom End of Line sequence.

Return value

Returns the length of the written string or false on failure.

Example

A runnable snippet:

$list = [ ['aaa', 'bbb', 'ccc', 'dddd'], ['123', '456', '789'], ['"aaa"', '"bbb"'] ]; $fp = fopen('file.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields, ',', '"', ''); } fclose($fp);

Output:

aaa,bbb,ccc,dddd 123,456,789 """aaa""","""bbb"""

Changelog

VersionChange
8.4.0Relying on the default value of escape is now deprecated.
8.1.0The optional eol parameter has been added.
7.4.0The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

See also

fgetcsv(), str_getcsv()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page fputcsv() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.