Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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|false

Parameters

ParameterTypeDescription
$streamresourceA handle to an opened file.
$length?intOptional. The maximum line length.
$separatorstringOptional. The field separator.
$enclosurestringOptional. The quote character.
$escapestringThe 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 = 400

Notes

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

  • fputcsv — Writes an array to a file as a CSV line.
  • fopen — Opens a file for reading or writing piece by piece.
  • explode — Splits a string into an array by a separator.

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.