Library contents

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

  1. Start with CSV row containing A,2
  2. Do this Parse the two fields
  3. Result A and 2
The comma marks the field boundary. A header can supply names for those fields.

Syntax

PHP 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.

From the programdeclare(strict_types=1)
First output linebolts, steel 3
lesson.php
<?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);
}
Output
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.

PHP documentation for fgetcsv

Advertisements

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?

Given"clay, red",7
Worked resultclay, red

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?

Given"lead, stereo",2
Worked resultlead, stereo