CSV files

A CSV file is plain text with one row per line, and PHP reads and writes it with two stream calls. The examples below write their own file first, so every row and every line of output can be checked here.

fgetcsv

Function fgetcsv reads one row from an open file handle and splits it into fields. It handles quoted values and embedded commas for you.

Open the file in read mode, read rows in a loop, and always close the handle when done.

Since PHP 8.4 a call that leaves the escape argument out is deprecated, because its default value will change: name the delimiter, the quote and an empty escape explicitly, as every example here does.

<?php file_put_contents(__DIR__ . "/data.csv", "name,city\nAda,London\nBob,Paris\n"); $handle = fopen(__DIR__ . "/data.csv", "r"); $header = fgetcsv($handle, 0, ",", '"', ""); $row = fgetcsv($handle, 0, ",", '"', ""); fclose($handle); echo implode(" ", $header), PHP_EOL; echo $row[0], " ", $row[1], PHP_EOL;

php read.php

name city
Ada London

The first call takes the header and the second one the first data row, which is why the output shows both lines and the fields keep their own values.

fputcsv

Function fputcsv does the reverse and writes an array as one CSV row. It adds quotes and escapes only where needed.

Open the file in write mode and pass each row as a plain array. The function takes care of formatting.

<?php $handle = fopen(__DIR__ . "/out.csv", "w"); fputcsv($handle, ["name", "score"], ",", '"', ""); fputcsv($handle, ["Ada, the first", "42"], ",", '"', ""); fclose($handle); echo file_get_contents(__DIR__ . "/out.csv");

php write.php

name,score
"Ada, the first",42

The comma inside the name is the whole point: fputcsv() puts quotes around that field, so a reader splits the row back into two values.

Delimiters

Not every CSV file uses a comma. Many exports use a semicolon, a tab, or a pipe to avoid conflicts with decimal commas.

Pass the delimiter as the third argument. Keep the same delimiter for reading and writing one data feed.

<?php file_put_contents(__DIR__ . "/eu.csv", "Ada;1,5\nBob;2,5\n"); $handle = fopen(__DIR__ . "/eu.csv", "r"); $row = fgetcsv($handle, 0, ";", '"', ""); fclose($handle); echo $row[0], " ", $row[1], PHP_EOL;

php eu.php

Ada 1,5

The semicolon separates the fields, so the decimal comma stays inside the second one instead of starting a new field.

Stream big files

Large exports do not fit in memory at once. Read and process them one row at a time inside a loop.

This pattern keeps memory flat no matter how many rows the file has. It works for imports, reports, and migrations.

<?php file_put_contents(__DIR__ . "/big.csv", "Ada,1\nBob,2\nCy,3\n"); $handle = fopen(__DIR__ . "/big.csv", "r"); while (($row = fgetcsv($handle, 0, ",", '"', "")) !== false) { echo $row[0], PHP_EOL; } fclose($handle);

php stream.php

Ada
Bob
Cy

One line leaves the loop per row and nothing else is kept, so the same code reads a file of three rows and one of three million.

Exercises

  1. Skip the header in the stream example and print only the data rows.
  2. Write a row with a semicolon inside a field and read it back with the comma delimiter.
  3. Count the fields of each row and print a warning for a row with the wrong number.
  4. Remove the escape argument from one call and read the deprecation message the run prints.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does fgetcsv() return at the end of the file?

    Answer

    false

    The loop condition compares with false, which is how the function marks the end of the rows.

  2. What is the third argument of fgetcsv()?

    Answer

    The field delimiter

    The signature is fgetcsv($handle, $length, $separator, $enclosure, $escape), so the delimiter comes third.

  3. Why does fputcsv() put quotes around Ada, the first?

    Answer

    The field carries the delimiter, so quotes keep it one value

    A comma inside the text would split the row, and the quotes tell a reader that the comma is data.

  4. Why does the stream example keep memory flat?

    Answer

    It reads one row per loop pass

    The handle holds a position in the file, so only the current row is in memory.

  5. What does this program print? <?php file_put_contents(__DIR__ . "/d.csv", "a,b\nc,d\n"); $handle = fopen(__DIR__ . "/d.csv", "r"); $row = fgetcsv($handle, 0, ",", '"', ""); fclose($handle); echo $row[0], " ", $row[1];

    Answer

    a b

    The first call reads the first line, and the two fields come back as the first two array elements.

  6. What does this program print? <?php $handle = fopen(__DIR__ . "/out.csv", "w"); fputcsv($handle, ["Ada", "42"], ",", '"', ""); fclose($handle); echo file_get_contents(__DIR__ . "/out.csv");

    Answer

    Ada,42

    Neither field needs quotes, so the row is written with the delimiter only and no surrounding quotes.

  7. What does this program print? <?php file_put_contents(__DIR__ . "/eu.csv", "Ada;1,5\n"); $handle = fopen(__DIR__ . "/eu.csv", "r"); $row = fgetcsv($handle, 0, ";", '"', ""); fclose($handle); echo count($row), " ", $row[1];

    Answer

    2 1,5

    The semicolon is the only delimiter, so the decimal comma stays inside the second field.

  8. What does this program print? <?php file_put_contents(__DIR__ . "/big.csv", "Ada,1\nBob,2\nCy,3\n"); $handle = fopen(__DIR__ . "/big.csv", "r"); $lines = 0; while (($row = fgetcsv($handle, 0, ",", '"', "")) !== false) { $lines++; } fclose($handle); echo $lines;

    Answer

    3

    Three rows are read, and the fourth call returns false without counting.

  9. What happens to a call of fgetcsv() that leaves the escape argument out on PHP 8.4 and later?

    Answer

    PHP prints a deprecation notice, because the default will change

    The deprecation names the missing $escape argument, which is why every example passes an empty string for it.

  10. Why is implode(",", $row) a bad way to write a CSV row?

    Answer

    A field that holds a comma or a quote breaks the row

    Joining strings cannot know which commas are data, while fputcsv() quotes exactly the fields that need it.

The examples call fgetcsv(), fputcsv() and implode(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.

Article author: Arthur Isaev