Skip to content

Instantly share code, notes, and snippets.

@balsama
Created January 29, 2025 03:09
Show Gist options
  • Save balsama/41dbbc146bd60402bdde9881c5c8a3a8 to your computer and use it in GitHub Desktop.
Save balsama/41dbbc146bd60402bdde9881c5c8a3a8 to your computer and use it in GitHub Desktop.
CSV writer helper method
/**
* Writes an array of arrays to a CSV file.
*
* @param string[] $headers
* The names of the table columns. Pass an empty array if you don't want any headers (e.g. if you're appending to
* an existing file.
* @param array[] $data
* Data to write. Each top-level array should contain an array the same length as the $header array.
* @param string $filename
* @param bool $append
* Whether to append to the file if it exist or overwrite from the beginning of the file.
* @param string $path
*/
public static function csv(array $headers, array $data, string $filename, $append = false, $path = 'data/')
{
if ($headers && $data) {
if (count($headers) !== count(reset($data))) {
throw new \InvalidArgumentException(
'The length of the `$header` array must equal the length of each of the arrays in `$data`'
);
}
}
$mode = ($append) ? 'a' : 'w';
$fp = fopen($path . $filename, $mode);
if ($headers) {
if ($append === false) {
fputcsv($fp, $headers);
}
else {
if (filesize($path . $filename) === 0) {
fputcsv($fp, $headers);
}
}
}
foreach ($data as $datum) {
fputcsv($fp, $datum);
}
fclose($fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment