How to write data to a CSV file
Short answer
Open the file for writing and pass rows to fputcsv():
<?php
$file = sys_get_temp_dir() . '/recipe-export.csv';
$handle = fopen($file, 'w');
fputcsv($handle, ['name', 'price'], ',', '"', '');
fputcsv($handle, ['Tea', 250], ',', '"', '');
fputcsv($handle, ['Coffee, ground', 400], ',', '"', '');
fclose($handle);
echo file_get_contents($file);Output:
name,price
Tea,250
"Coffee, ground",400Headers from the keys
For an array of records the first row comes from the keys:
<?php
$rows = [['name' => 'Tea', 'price' => 250], ['name' => 'Juice', 'price' => 180]];
$file = sys_get_temp_dir() . '/recipe-export.csv';
$handle = fopen($file, 'w');
fputcsv($handle, array_keys($rows[0]), ',', '"', '');
foreach ($rows as $row) {
fputcsv($handle, $row, ',', '"', '');
}
fclose($handle);
echo file_get_contents($file);Output:
name,price
Tea,250
Juice,180Non-ASCII text in Excel
For Excel to open a UTF-8 file correctly, write three bytes at the very start — the BOM: fwrite($handle, "\xEF\xBB\xBF").