fgetcsv
Reads a line of a CSV file and splits it into fields.
Syntax
fgetcsv(resource $stream, ?int $length = null, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $stream | resource | A handle to an opened file. |
| $length | ?int | Optional. The maximum line length. |
| $separator | string | Optional. The field separator. |
| $enclosure | string | Optional. The quote character. |
| $escape | string | The escape character; pass an empty string. |
Return value
array|falseAn array of fields, or `false` at the end of the file.
Examples
Reading a table from CSV:
<?php
$file = sys_get_temp_dir() . '/ref-read.csv';
file_put_contents($file, "name,price\nTea,250\n\"Coffee, black\",400\n");
$handle = fopen($file, 'r');
$header = fgetcsv($handle, null, ',', '"', '');
while (($row = fgetcsv($handle, null, ',', '"', '')) !== false) {
echo $row[0], ' = ', $row[1], "\n";
}
fclose($handle);Output:
Tea = 250
Coffee, black = 400Notes
The function correctly parses quoted fields with commas inside — explode(',', $line) breaks on them. Some locales of Excel save CSV with a semicolon separator.
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.