CSV files
fgetcsv
Function fgetcsv reads one row from an open file handle and splits it into fields. It handles quoted values and embedded commas for you.
Open the file in read mode, read rows in a loop, and always close the handle when done.
Since PHP 8.4 the default escape character is deprecated: name the delimiter, the quote and an empty escape explicitly, as every example here does.
$handle = fopen("data.csv", "r");
$row = fgetcsv($handle, 0, ",", '"', "");
fclose($handle);
echo $row[0];
fputcsv
Function fputcsv does the reverse and writes an array as one CSV row. It adds quotes and escapes only where needed.
Open the file in write mode and pass each row as a plain array. The function takes care of formatting.
$handle = fopen("out.csv", "w");
fputcsv($handle, ["name", "score"], ",", '"', "");
fputcsv($handle, ["Ada", "42"], ",", '"', "");
fclose($handle);
echo "done";
Delimiters
Not every CSV file uses a comma. Many exports use a semicolon, a tab, or a pipe to avoid conflicts with decimal commas.
Pass the delimiter as the third argument. Keep the same delimiter for reading and writing one data feed.
$handle = fopen("eu.csv", "r");
$row = fgetcsv($handle, 0, ";", '"', "");
fclose($handle);
echo $row[0];
Stream big files
Large exports do not fit in memory at once. Read and process them one row at a time inside a loop.
This pattern keeps memory flat no matter how many rows the file has. It works for imports, reports, and migrations.
$handle = fopen("big.csv", "r");
while (($row = fgetcsv($handle, 0, ",", '"', "")) !== false) {
echo $row[0] . "\n";
}
fclose($handle);
Next: Harden sessions
Автор статьи: Arthur Isaev