Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP str_getcsv() function

Reference for PHP str_getcsv(): parse one line of CSV text into an array, change the separator and quote, the escape parameter, and what it cannot do for whole files.

str_getcsv() parses a string that holds CSV data and returns an array of fields. Quoted fields, doubled quotes and separators inside quotes are handled correctly. It is the quick way to split a single line that is already in memory.

It parses one record. If the string contains several lines, a newline outside quotes simply ends up inside the last field instead of starting a new record. For whole files, read with fgetcsv() in a loop.

PHP
$fields = str_getcsv('Ada,36,"London, UK"', escape: "");
// ["Ada", "36", "London, UK"]

Try it

PHP Quotes, separators and empty fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Parsing a multi-line string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
str_getcsv(
    string $string,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\"
): array
Name Description
$string The text of one CSV record.
$separator A single-character field separator.
$enclosure A single-character quote.
$escape The escape character; use "" to disable the legacy backslash escaping.

Return value: an array of strings. An empty input string gives [null].

Errors: a ValueError is thrown when $separator or $enclosure is not exactly one byte.

Usage notes

  • Pass escape: "" for standard CSV. Omitting the argument is deprecated since PHP 8.4.
  • One record only. Do not split a multi-line string with explode("\n") if quoted fields may contain line breaks; put the text in a php://memory stream and use fgetcsv().
  • Fields stay strings, and spaces around values are kept: "10, 20" yields "10" and " 20". intval() ignores the leading space, trim() removes it.
  • An empty string returns [null], not an empty array, so check for it when reading user input.
  • Unbalanced quotes do not raise an error; the parser takes the rest of the string as the field.
  • Not a validator. Malformed CSV is accepted in a best-effort way, so check the number of fields yourself.
  • Writing CSV is the job of fputcsv().