Skip to content

Instantly share code, notes, and snippets.

@twysto
Last active October 28, 2024 15:27
Show Gist options
  • Save twysto/5baec9934b54e456893d to your computer and use it in GitHub Desktop.
Save twysto/5baec9934b54e456893d to your computer and use it in GitHub Desktop.
<?php
function exportCSV(
iterable $items,
array $allowed_columns,
?string $sep = ';',
?string $filename = 'export.csv',
) {
$output = 'sep=' . $sep . PHP_EOL;
foreach ($allowed_columns as $i => $allowed_column) {
$output .= ($i > 0 ? $sep : '') . ucfirst($allowed_column);
}
$output .= PHP_EOL;
foreach ($items as $line) {
$i = 0;
foreach ($line as $column_name => $column_value) {
if (in_array($column_name, $allowed_columns)) {
$output .= ($i > 0 ? $sep : '') . $column_value;
$i++;
}
}
$output .= PHP_EOL;
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
print_r(mb_convert_encoding($output, "UTF-8", mb_detect_encoding($output)));
//exit;
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~
* Usage:
* ~~~~~~~~~~~~~~~~~~~~~~
*/
$items = [
0 => [ 'firstname' => 'Alice', 'lastname' => 'Henderson', 'email' => '[email protected]' ],
1 => [ 'firstname' => 'John', 'lastname' => 'Doe', 'email' => '[email protected]' ],
2 => [ 'firstname' => 'Bob', 'lastname' => 'Sanders', 'email' => '[email protected]' ],
];
// Or just:
// $items = $this->_dao->findItems(); // Query Database
exportCSV(
$items,
[ 'firstname'/*, 'lastname',*/ 'email' ], // The 'lastname' column should be excluded
// ';', // The separator of your choice (Default: ';')
// 'custom_export_name.csv', // The filename of your choice (Default: 'custom_export_name.csv')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment