Codectionary / Developer documentation / PHP

PHP CSV stream parsing

fgetcsv understands quoted delimiters and CSV records that a plain comma split cannot parse. An empty escape argument disables PHP-specific backslash escaping and is explicitly supplied here.

Syntax

fgetcsv($stream, 0, ",", "\"", "")

Examples

PHP CSV stream parsing

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$stream = fopen('php://temp', 'w+');
if ($stream === false) throw new RuntimeException('Cannot open stream');
try {
    fwrite($stream, "name,city\nAda,\"London, UK\"\n");
    rewind($stream);
    fgetcsv($stream, 0, ',', '"', ''); // header
    $row = fgetcsv($stream, 0, ',', '"', '');
    if ($row !== false) echo $row[1], PHP_EOL;
} finally { fclose($stream); }
  1. Output: London, UK. The comma inside quotes belongs to one field; the temporary stream is closed even on failure.

Best practices

  • Validate column count and field values after parsing. Explicitly pass escape rather than relying on its deprecated default in PHP 8.4+.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading