PHP fgetcsv
fgetcsv reads a CSV record from a stream and returns its fields as an array. It handles delimiters inside quoted values.
A simple example
fgetcsv
- Start with CSV row containing A,2
- Do this Parse the two fields
- Result A and 2
Syntax
$row = fgetcsv($stream, null, ',', '"', '')
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Read an invoice containing a quoted comma
A supplier sends a CSV invoice whose quoted description contains a comma. Use a CSV reader that understands quoting so the amount stays in its proper column and the description remains intact.
<?php
declare(strict_types=1);
$stream = fopen('php://temp', 'w+');
if ($stream === false) throw new RuntimeException('Cannot open temporary stream');
try {
fwrite($stream, "\"bolts, steel\",3\nnuts,1\n");
rewind($stream);
while (($row = fgetcsv($stream, null, ',', '"', '')) !== false) {
printf("%s %s\n", $row[0], $row[1]);
}
} finally {
fclose($stream);
}
bolts, steel 3 nuts 1
An explicit empty escape argument uses doubled quotation marks inside quoted fields and avoids relying on the legacy default. The temporary stream makes the example runnable as a single file.
Read an exhibit order
A curator enters a material and finish together inside a quoted item name. Read the quoted field as one CSV cell. What item name belongs to this row?
Read a studio purchase
A technician enters a cable description with a comma inside the field. Read the quoted field as one CSV cell. What item name belongs to this row?