← All writing

Read CSV safely in modern PHP: quoted commas and explicit escape settings

PHP 8.3+; relevant to 8.4 deprecationsSources checked 2026-09-12

A product name contains a comma: "Washer, stainless". Splitting each line with explode creates an extra column and can shift the stock count into the wrong field. CSV needs a CSV parser.

Reproduce the quoted-field case

<?php
$stream = fopen('php://temp', 'w+');
fwrite($stream, "sku,name,stock\nAX-204,\"Washer, stainless\",8\n");
rewind($stream);
$header = fgetcsv($stream, null, ',', '"', '');
$row = fgetcsv($stream, null, ',', '"', '');
fclose($stream);
assert($header === ['sku', 'name', 'stock']);
assert($row === ['AX-204', 'Washer, stainless', '8']);
echo $row[1], PHP_EOL;

The last argument explicitly disables the proprietary escape character. This example assumes conventional CSV quoting with doubled quote characters. Confirm the supplier's format before choosing a different setting.

Validate structure before combining columns

Check the header exactly against the expected contract, or map a documented set of names. Reject duplicate headers. Check that each row has the required number of columns before combining it with the header.

The string "8" still needs stock validation. Reading CSV does not establish integer range, allowed currency, a unique SKU, or permission to overwrite the catalog. Keep parsing and business validation as separate steps.

Blank lines can produce a row containing null rather than a useful record. Track source row numbers so the error report can say which row needs correction. Keep an import summary with accepted, rejected, and duplicate counts.

A useful regression fixture

Include a quoted comma, a doubled quote, a blank line, an extra column, and a missing stock value. Avoid testing only the happy path exported by your own code. Real suppliers often expose the assumptions that your exporter never violates.

PHP 8.4 deprecated relying on the default escape argument. The fgetcsv manual describes explicit escape behavior, blank lines, and compatibility concerns.