W3docs

str_getcsv()

Learn the PHP str_getcsv() function: syntax, parameters, worked examples, parsing multi-line CSV, handling quoted fields, and common pitfalls.

The str_getcsv() function parses a single line of CSV (comma-separated values) text and returns its fields as a flat array. It is the in-memory counterpart of fgetcsv(): instead of reading a line from an open file handle, it works on a string you already have — a row pasted from a form, a single line read from an API response, or one element of an array you split yourself.

Because real CSV is harder than it looks (fields can be wrapped in quotes, contain commas, or span the delimiter), str_getcsv() is almost always the right choice over a naive explode(',', $line), which breaks on any quoted comma.

Syntax

str_getcsv(
    string $string,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\"
): array
ParameterRequiredDescription
$stringYesThe CSV line to parse.
$separatorNoThe field delimiter — a single character. Default ,.
$enclosureNoThe character that wraps fields containing the delimiter, quotes, or newlines. Default ".
$escapeNoThe escape character. Default \. Pass "" to disable PHP's proprietary escaping (recommended for strict RFC 4180 CSV).

The function always returns an array. A field that is empty becomes an empty string (""); an entirely empty input line returns [null].

Basic example

php— editable, runs on the server

Output:

Array
(
    [0] => John
    [1] => Doe
    [2] => 25
)

Each comma-separated value becomes one element, indexed from 0.

Quoted fields and embedded commas

This is where str_getcsv() earns its keep. A field wrapped in double quotes may contain the delimiter without splitting:

<?php
$input = '"Doe, John","New York, NY",25';
$array = str_getcsv($input);

print_r($array);
?>

Output:

Array
(
    [0] => Doe, John
    [1] => New York, NY
    [2] => 25
)

The enclosing quotes are stripped, and the commas inside them are kept as data. explode(',', $input) would have wrongly produced five elements here.

Using a different delimiter and enclosure

Many "CSV" files are actually semicolon- or tab-separated. Override the second and third arguments to match:

<?php
$input = "'Jane Doe';'Berlin';30";
$array = str_getcsv($input, ';', "'");

print_r($array);
?>

Output:

Array
(
    [0] => Jane Doe
    [1] => Berlin
    [2] => 30
)

For a tab-separated line use "\t" as the separator.

Parsing a multi-line CSV string

str_getcsv() parses one line at a time. To turn a whole CSV document into rows, split it into lines first, then map each line through the function. Combining it with array_map() keeps this concise:

<?php
$csv = "name,city,age\nJohn,Boston,25\nJane,Berlin,30";

$rows = array_map('str_getcsv', explode("\n", $csv));

print_r($rows);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => name
            [1] => city
            [2] => age
        )

    [1] => Array
        (
            [0] => John
            [1] => Boston
            [2] => 25
        )

    [2] => Array
        (
            [0] => Jane
            [1] => Berlin
            [2] => 30
        )

)

Note: explode("\n", ...) is a simple split. If your file uses Windows line endings (\r\n) or fields contain newlines inside quotes, prefer reading the file with fgetcsv() in a loop, which handles those cases natively.

Mapping rows to a header

A common pattern is to use the first row as keys and build associative arrays with array_combine():

<?php
$lines  = ['name,city,age', 'John,Boston,25', 'Jane,Berlin,30'];
$header = str_getcsv(array_shift($lines));

$people = [];
foreach ($lines as $line) {
    $people[] = array_combine($header, str_getcsv($line));
}

print_r($people[0]);
?>

Output:

Array
(
    [name] => John
    [city] => Boston
    [age] => 25
)

Common pitfalls

  • One line only. Passing a multi-line string treats the whole thing as a single record, so always split into lines yourself before parsing.
  • The escape character surprises people. PHP's default \ escaping is non-standard. For data that follows RFC 4180 (where " is escaped by doubling it, as ""), pass escape: "" to avoid backslashes being swallowed.
  • Numbers stay strings. Every field comes back as a string ("25", not 25). Cast explicitly when you need real numbers.
  • Trailing newline. A line read with a trailing \n may produce an empty last field; trim the input first if needed.
  • fgetcsv() — read and parse a CSV line directly from a file handle.
  • fputcsv() — write an array to a file as a CSV line (the inverse).
  • explode() — split a string by a delimiter when there are no quoted fields to worry about.
  • file_get_contents() — load a CSV file into a string to feed str_getcsv().

Practice

Practice
What does the str_getcsv() function in PHP do?
What does the str_getcsv() function in PHP do?
Was this page helpful?