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
Syntax
str_getcsv(string $string, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array
Parameters
| Parameter | Description |
|---|---|
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
<?php
print_r(str_getcsv('Ada,"London, UK","She said ""hi"""', escape: ""));
Output
Array
(
[0] => Ada
[1] => London, UK
[2] => She said "hi"
)<?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 withfgetcsv(). - Pass
escape: ""for standard (RFC 4180) CSV; from PHP 8.4, leavingescapeout is deprecated.
Version history
Related
explode()· Split a string into an array by a separator, like turning "a,b,c" into ["a", "b", "c"]. A limit caps the pieces.implode()· Join array elements into one string with a separator between them. join() is an alias of implode().- PHP Strings · tutorial