Tags: PHP
I wrote this quick function while waiting for an appointment at the doctor's office. Really handy for downloading data in csv format. Just declare the right headers and put your array through this function.
public function array2csv(array &$array)
{
if (empty($array)) {
return null;
}
ob_start();
$downloadFile = fopen("php://output", 'w');
fputcsv($downloadFile, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($downloadFile, $row);
}
fclose($downloadFile);
return ob_get_clean();
}
©2023, kirillsimin.com