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
| Parameter | Type | What it takes |
|---|---|---|
| $stream | resource | The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). |
| $fields | array | An array of strings. |
| $separator | string | The separator parameter sets the field separator. It must be a single byte character. |
| $enclosure | string | The enclosure parameter sets the field enclosure character. It must be a single byte character. |
| $escape | string | The 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. |
| $eol | string | The 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
| Version | Change |
|---|---|
| 8.4.0 | Relying on the default value of escape is now deprecated. |
| 8.1.0 | The optional eol parameter has been added. |
| 7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism. |
See also
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.