PHP 8 reference · String Functions

PHP str_getcsv() Function

Parse one line of CSV text into an array of fields, handling quoted values that contain commas or quotes.

PHP 8 Since 5.3

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

str_getcsv(string $string, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array

Parameters

ParameterDescription
string The input string.
separator optional The field separator. Default: ","
enclosure optional The quote character. Default: '"'
escape optional The escape character; pass "" for standard CSV. Default: "\\"

Return value

An array of fields.

Examples

Quoted fieldsTry it yourself
<?php
print_r(str_getcsv('Ada,"London, UK","She said ""hi"""', escape: ""));

Output

Array
(
    [0] => Ada
    [1] => London, UK
    [2] => She said "hi"
)
Another separatorTry it yourself
<?php
$csv = "name;age\nAda;36\nAlan;41";
foreach (explode("\n", $csv) as $line) {
    echo implode(" | ", str_getcsv($line, ";", escape: "")), "\n";
}

Output

name | age
Ada | 36
Alan | 41

Common mistakes

  • Splitting the whole file by "\n" breaks fields that contain new lines. For files, read rows with fgetcsv().
  • Pass escape: "" for standard (RFC 4180) CSV; from PHP 8.4, leaving escape out is deprecated.

Version history

VersionChange
PHP 5.3Added
PHP 8.4Leaving out escape is deprecated, because its default value will change.

Was this page helpful?