PHP CSV Files
What Is a CSV File?
In simple terms: A CSV (Comma-Separated Values) file stores a table as plain text: one row per line, with values separated by commas. Spreadsheet programs such as Excel, Google Sheets, and LibreOffice can open and save CSV files, which makes CSV the most common format for importing and exporting data.
id,name,price
1,Gel Pen,20
2,Notebook,60
Technically: CSV is described in RFC 4180. Values containing the separator, double quotes, or line breaks are wrapped in double quotes, and double quotes inside values are doubled (""). PHP's fgetcsv(), fputcsv(), and str_getcsv() implement these rules, so you should never split or build CSV lines manually with explode() and implode().
Why Not Just Use explode(',')?
<?php
$line = '1,"Desk Lamp, LED",1299';
print_r(explode(',', $line));
print_r(str_getcsv($line, escape: ''));
Output
Array
(
[0] => 1
[1] => "Desk Lamp
[2] => LED"
[3] => 1299
)
Array
(
[0] => 1
[1] => Desk Lamp, LED
[2] => 1299
)
explode() breaks the quoted product name into two broken fields. str_getcsv() understands the quotes and returns the correct three values.
The escape Parameter
PHP's CSV functions historically used a non-standard backslash escape character (