The following method seems to do the trick for me. Microsoft Excel opens it perfectly.
$filePath = '/home/user/'; $filename = 'test.csv'; $df = fopen($filePath.$filename, 'w'); fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF)); fputcsv($df, $dataColumns); foreach ($dataArray as $dataRow) { fputcsv($df, $dataRow); } fclose($df); // Output csv header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename='.$filename); header("Cache-Control: no-store, no-cache"); readfile($filePath.$filename); Notes
- the line
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));writes file header for correct encoding. - You can use the third parameter of
fputcsv(...)to set the delimiter.