Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 147 · Working with Files

CSV Files

Read and write CSV files in PHP with fgetcsv, fputcsv and str_getcsv - turn headers into associative arrays, set the escape parameter and handle Excel, BOMs and semicolons.

CSV ("comma-separated values") is the plain-text table format that everything understands. Spreadsheets export it, banks offer statements in it, analytics tools import it, and when a client asks "can I get that as an Excel file?", a CSV is often the quickest honest answer. Each line is a row, and commas separate the fields:

TEXT
sku,name,price
MUG-01,Coffee mug,8.50
CAP-07,"Cap, blue",12.00

It looks so simple that people are tempted to read it with explode(',', $line). That breaks the moment a field contains a comma ("Cap, blue"), a quote or a line break, which is why the format has quoting rules and PHP has dedicated functions that follow them: fputcsv() writes rows, fgetcsv() reads them from a file, and str_getcsv() parses a string. This lesson covers all three, how to turn rows into associative arrays, the escape parameter that PHP 8.4 asks you to set, and the quirks of Excel.

How CSV quoting works

The common rules (written down in RFC 4180) are short:

  • Fields are separated by a delimiter, usually a comma.
  • A field that contains the delimiter, a double quote or a line break is wrapped in double quotes: "Cap, blue".
  • A double quote inside a quoted field is written twice: "The ""best"" mug" means The "best" mug.
  • Rows end with a line break. RFC 4180 says \r\n; most tools also accept \n.

You never have to apply these rules by hand. fputcsv() adds quotes exactly where they're needed and fgetcsv() removes them.

The escape parameter (set it to an empty string)

All three CSV functions have a parameter called $escape. Its default is a backslash, a PHP-specific extension that isn't part of standard CSV: a backslash before a quote changes how that quote is read and written. The result is files that other programs read differently from PHP, and data that doesn't survive a round trip. PHP 8.4 therefore deprecated relying on the default: if you don't pass $escape, you get a Deprecated message, because the default will change in a future version.

Pass escape: '' (an empty string) to switch the extension off and get standard CSV. Every example in this lesson does that with a named argument. Here is what goes wrong without it:

PHP Why escape should be an empty string

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output starts with a Deprecated: fputcsv(): the $escape parameter must be provided as its default value will change message for line 10, the call without escape:, which is the point of this example. Then compare the two lines:

TEXT
escape off: C:\temp\,"say ""hi""","path\""quoted"
default:    "C:\temp\","say ""hi""","path\"quoted"

With the default, the backslashes in the first field even force quotes around it, and the quote after the backslash in the third field isn't doubled, so any standard CSV reader (Excel, Python, a database import) sees a broken field there. With escape: '' every quote is doubled and the file is valid. (The php://memory stream used here is an in-memory file; see Streams and Wrappers.)

Writing CSV with fputcsv

fputcsv($handle, $fields) formats one array as a CSV line and writes it to an open file handle. Write the header row first, then one call per record:

PHP Writing a CSV file

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is a valid CSV file:

TEXT
sku,name,price,stock
MUG-01,"Coffee mug",8.50,40
CAP-07,"Cap, blue",12.00,0
PEN-02,"The ""best"" pen",2.25,310

fputcsv() quoted Cap, blue because of the comma and The ""best"" pen because of the quotes. It also quotes any field containing a space, like "Coffee mug", which is allowed (quotes around any field are always valid) and harmless. Numbers are written the way PHP converts them to strings, so the example formats prices with number_format() to keep two decimals: 8.5 would otherwise be written as 8.5.

The full signature is fputcsv($handle, $fields, $separator = ',', $enclosure = '"', $escape, $eol = "\n"). The eol parameter (PHP 8.1) sets the line ending; pass eol: "\r\n" if a strict consumer insists on RFC 4180 line endings.

Reading CSV with fgetcsv

fgetcsv($handle) reads the next row from a file handle and returns it as an array of strings. At the end of the file it returns false, so the reading loop has the same shape as the fgets() loop:

PHP Reading rows with fgetcsv

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at what fgetcsv() handled for you: the comma inside "Great work, keep going", the doubled quotes around why?, and the line break inside the last comment, which spans two physical lines but is one field. That last case is something no line-by-line explode() could ever get right.

Two details to remember:

  • Blank lines come back as an array with a single null, [null], not as an empty array. Skip them explicitly, as the example does.
  • Every value is a string, including 91. Convert numbers yourself with (int) or (float) once you've validated them; see Type Juggling and Casting.

Rows as associative arrays

Working with $row[1] is fragile: if someone adds a column, every index shifts. The standard pattern reads the header row first and uses array_combine() to pair each value with its column name:

PHP Turning rows into associative arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The header id, customer, total has spaces after the commas, which would make the keys ' customer'; array_map('trim', ...) fixes that common export quirk. array_combine() throws a ValueError if the two arrays have different lengths, so the function checks the field count itself and reports the line number, a much more helpful message for whoever has to fix the file: Import failed: Line 2 has 2 fields, expected 3. The sum line uses array_column() to pull one column out of all the records and prints 144.8.

Parsing a string with str_getcsv

When the CSV is already in a string, such as a single line from an API, a form textarea or a database field, use str_getcsv($string). It parses one record:

PHP
$fields = str_getcsv('MUG-01,"Coffee mug, large",8.50', escape: '');
// ['MUG-01', 'Coffee mug, large', '8.50']

To parse a whole multi-line string, don't split it on "\n" yourself, since quoted fields can contain line breaks. Write it into a php://temp stream and use fgetcsv():

PHP Parsing CSV text from a string

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second part reads a semicolon-separated file with decimal commas, the format spreadsheets produce in many European locales. The separator: ';' argument handles the first, and str_replace(',', '.', ...) converts -3,5 into a number PHP understands. Note that str_pad() counts bytes, so São Paulo (with a two-byte ã) gets no padding at all and runs into the number, because its 9 characters are 10 bytes; Unicode and Multibyte Strings explains why and how mb_str_pad() fixes it.

Excel quirks: separators and the BOM

Excel is the most common consumer of the CSV files you generate, and it has two well-known habits.

The separator depends on the user's locale. In regions where the decimal separator is a comma (much of Europe, South America), Excel expects semicolons between fields and puts a whole comma-separated line into a single column. If your users are in those regions, write with separator: ';' and decimal commas, or offer both formats.

Excel assumes the old Windows encoding, not UTF-8, unless the file starts with a byte order mark (BOM), the three bytes EF BB BF. Without it, Zoë and € turn into garbage like Zoë. So when you write a CSV for Excel, write the BOM first. And when you read a CSV that came from Excel, strip the BOM, or your first column name will secretly start with three invisible bytes and $row['id'] won't be found:

PHP Writing and stripping a UTF-8 BOM

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The file begins with efbbbf followed by 6964 (id). Read back naively, the first header is string(5) "id": it looks like id but is five bytes long, so the comparison is false. After removing the BOM, it's true and the lookup works. Stripping the BOM is a one-liner worth putting in every CSV import.

To offer a CSV as a download on a website, send headers before the content: header('Content-Type: text/csv; charset=UTF-8'); and header('Content-Disposition: attachment; filename="export.csv"');, then open php://output with fopen() and fputcsv() straight into the response. HTTP Headers explains header().

Large files and CSV injection

Large files: fgetcsv() reads one row at a time, so memory stays flat no matter how big the file is, as long as you don't collect every row into an array. For an import of a million rows, process each row inside the loop (insert into the database in batches, update counters), or wrap the loop in a generator that yields one record at a time.

CSV injection: if a field written to a CSV starts with =, +, -, @, a tab or a carriage return, spreadsheet programs may treat it as a formula when the file is opened. A user who registers with the name =HYPERLINK("http://evil.example","Click") can plant a link (or worse) in your admin's export. When exporting user-supplied text for spreadsheets, prefix such values with a single quote:

PHP
function spreadsheetSafe(string $value): string
{
    return preg_match('/^[=+\-@\t\r]/', $value) ? "'" . $value : $value;
}

Apply it only to free-text fields, not to numbers like -5, which you write as numbers anyway.

SplFileObject offers an object-oriented alternative for reading: new SplFileObject($path) with setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD) and setCsvControl(',', '"', '') lets you foreach over rows directly. It's the same parser underneath.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does fputcsv($h, ['Cap, blue', 'say "hi"'], escape: '') write?

    Fields with a comma or a quote are wrapped in double quotes, and quotes inside are doubled. That's standard CSV quoting.
  2. 2. What does fgetcsv() return for a blank line?

    A blank line returns [null]. false means the end of the file, so the loop must not stop on blank lines; skip them with a check like $row === [null].
  3. 3. Why does $row['id'] fail after combining an Excel CSV header naively?

    The three BOM bytes stick to the first header field. Strip them with substr when the field starts with "\xEF\xBB\xBF".
  4. 4. Why pass escape: '' to the CSV functions in PHP 8.4+?

    The default backslash escape produces CSV that other programs read differently. PHP 8.4 deprecated relying on it; an empty string gives standard CSV.
  5. 5. Why not read CSV with explode(',', $line) on each line from file()?

    "Cap, blue" would become two fields, doubled quotes would stay doubled, and a field with a line break would be split across two rows. fgetcsv handles all of that.

Summary

  • CSV quotes fields that contain the delimiter, a quote or a line break, and doubles quotes inside them. Let PHP's functions apply the rules; never explode() CSV.
  • Always pass escape: '': the backslash default is non-standard and relying on it is deprecated since PHP 8.4.
  • fputcsv($handle, $fields, escape: '') writes a row (separator:, enclosure: and eol: are configurable); write the header row first.
  • fgetcsv($handle, escape: '') reads the next row as an array of strings, false at the end and [null] for blank lines. Quoted multi-line fields are handled.
  • Combine the trimmed header with each row via array_combine() for associative records; check the field count first and report the line number.
  • str_getcsv() parses one record from a string; for multi-line text, write it to php://temp and use fgetcsv().
  • For Excel: write a UTF-8 BOM ("\xEF\xBB\xBF"), consider ; separators for comma-decimal locales, and strip the BOM when importing.
  • Process big files row by row, and protect spreadsheet exports from formula (CSV) injection.

Next: JSON