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|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $stream | resource | A handle to an opened file. |
| $fields | array | The field values. |
| $separator | string | Optional. The field separator. |
| $enclosure | string | Optional. The quote character. |
| $escape | string | The escape character; pass an empty string. |
| $eol | string | Optional. 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",400Notes
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
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.