W3docs

fgetcsv()

The fgetcsv() function in PHP is used to read a line from a file and parse it as CSV (Comma-Separated Values) data. It's a crucial function for server

Introduction to PHP fgetcsv() Function

The fgetcsv() function in PHP reads a single line from an open file and parses it as CSV (Comma-Separated Values), returning the fields as an array. It is the standard tool for importing spreadsheet exports, data feeds, and tabular text files into PHP.

The reason you reach for fgetcsv() instead of fgets() plus explode(',', ...) is that CSV is more subtle than splitting on commas. A field can contain a comma if it is wrapped in quotes ("Doe, John"), a field can span multiple lines, and quotes inside a quoted field are doubled (""). fgetcsv() handles all of these rules for you, so you get clean fields back without writing a parser.

This page covers the signature and parameters, the return values, and complete runnable examples — reading a whole file, using a custom delimiter, and mapping a header row to associative rows.

Syntax

The syntax of the fgetcsv() function is as follows:

The Syntax of PHP fgetcsv()

array fgetcsv ( resource $stream [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] )
  • stream: the file pointer to read from
  • length: the maximum length of the line to read
  • delimiter: the delimiter character for CSV data
  • enclosure: the enclosure character for CSV data
  • escape: the escape character for CSV data

Parameters

The fgetcsv() function takes one required parameter and four optional parameters:

  1. $stream: The file pointer you want to read from. This parameter can be a resource created using the fopen() function or a similar function.
  2. $length: The maximum length of the line to read. This parameter is optional and defaults to 0, which means that the entire line will be read.
  3. $delimiter: The delimiter character for CSV data. This parameter is optional and defaults to ','.
  4. $enclosure: The enclosure character for CSV data. This parameter is optional and defaults to '"'.
  5. $escape: The escape character for CSV data. This parameter is optional and defaults to '\'. Note: This parameter is deprecated as of PHP 8.1.

Return Values

On success, fgetcsv() returns an indexed array containing the fields read from the line. A blank line returns an array with a single null field. At the end of the file it returns false, which is how you know when to stop reading. If the stream is not valid it also returns false.

Because both "end of file" and "error" return false, the idiomatic way to loop is to keep calling fgetcsv() until it returns false — usually inside a while condition.

Examples

Example 1: Read a single line of CSV data

The following example opens a file, reads one line of CSV data, and properly closes the file handle. Always check that fopen() succeeded before reading:

Read a single line of CSV data

$fileHandle = fopen('data.csv', 'r');
if ($fileHandle !== false) {
    $row = fgetcsv($fileHandle);
    print_r($row);
    fclose($fileHandle);
}

For a file whose first line is John,Doe,42, this prints:

Array
(
    [0] => John
    [1] => Doe
    [2] => 42
)

Example 2: Loop over every row in a file

In real code you rarely read just one line. Call fgetcsv() in a while loop until it returns false to process the whole file:

Read every row of a CSV file

$fileHandle = fopen('data.csv', 'r');
if ($fileHandle !== false) {
    while (($row = fgetcsv($fileHandle)) !== false) {
        echo implode(' | ', $row), PHP_EOL;
    }
    fclose($fileHandle);
}

The strict !== false comparison matters: a valid row such as ["0"] is "falsy" in PHP, so a loose while ($row = fgetcsv(...)) would stop early on legitimate data.

Example 3: Use a custom delimiter

Many "CSV" files are actually semicolon- or tab-separated. Pass the delimiter as the third argument (the second argument, $length, can stay 0 for no limit):

Read CSV data with a custom delimiter

// Semicolon-separated values
$row = fgetcsv($fileHandle, 0, ';');

// Tab-separated values
$row = fgetcsv($fileHandle, 0, "\t");

Example 4: Map a header row to associative arrays

CSV files usually have a header row. Read it once, then combine it with each data row using array_combine() so you can access fields by name instead of by numeric index:

Turn a CSV file into associative rows

$fileHandle = fopen('users.csv', 'r');
if ($fileHandle !== false) {
    $header = fgetcsv($fileHandle); // e.g. ['id', 'name', 'email']
    while (($data = fgetcsv($fileHandle)) !== false) {
        $row = array_combine($header, $data);
        echo $row['name'], ' <', $row['email'], '>', PHP_EOL;
    }
    fclose($fileHandle);
}

Common Gotchas

  • The $escape parameter is deprecated. As of PHP 8.1, passing a non-empty $escape triggers a deprecation notice, and PHP 9 will change the default to "". For standards-compliant CSV (where quotes are escaped by doubling, ""), pass escape: "" explicitly.
  • UTF-8 BOM on the first field. Files exported from Excel may start with a byte-order mark, so the first header field can look like "\u{FEFF}id". Strip it with ltrim($header[0], "\u{FEFF}") if comparisons fail.
  • auto_detect_line_endings. Old Mac (\r) line endings can confuse the parser on older PHP; this ini setting was removed in PHP 8.1 because the parser now handles them natively.
  • fopen() — open the file before reading.
  • fgets() — read a raw line without CSV parsing.
  • fputcsv() — the inverse: write an array as a CSV line.
  • fclose() — close the handle when finished.
  • PHP File Handling — the bigger picture of working with files.

Conclusion

fgetcsv() reads one line from an open file and parses it as CSV, returning an indexed array of fields and false at end of file. Loop with a strict !== false check, use array_combine() to map a header row to named fields, and remember that the $escape parameter is deprecated — pass escape: "" for modern, standards-compliant parsing.

Practice

Practice
What is the function of fgetcsv() in PHP?
What is the function of fgetcsv() in PHP?
Was this page helpful?