Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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",400

Headers 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,180

Non-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").

Functions used in this recipe

  • fputcsv — Writes an array to a file as a CSV line.
  • fopen — Opens a file for reading or writing piece by piece.
  • fgetcsv — Reads a line of a CSV file and splits it into fields.

Thanks for reading!

Donate to the site — we work hard for you.