Skip to content

Instantly share code, notes, and snippets.

@LukeTowers
Created October 21, 2017 18:54
Show Gist options
  • Save LukeTowers/8b239f820150a8d2f35a17edb0e06c0a to your computer and use it in GitHub Desktop.
Save LukeTowers/8b239f820150a8d2f35a17edb0e06c0a to your computer and use it in GitHub Desktop.
October
$data = array_dot(\Lang::get('iacea.exchanges::lang'));
$options = [];
/*
* Parse options
*/
$defaultOptions = [
'firstRowTitles' => true,
'useOutput' => false,
'fileName' => 'export.csv',
'delimiter' => null,
'enclosure' => null,
'escape' => null
];
$options = array_merge($defaultOptions, $options);
$columns = ['code', 'translation'];
/*
* Prepare CSV
*/
$csv = CsvWriter::createFromFileObject(new SplTempFileObject);
$csv->setOutputBOM(CsvWriter::BOM_UTF8);
if ($options['delimiter'] !== null) {
$csv->setDelimiter($options['delimiter']);
}
if ($options['enclosure'] !== null) {
$csv->setEnclosure($options['enclosure']);
}
if ($options['escape'] !== null) {
$csv->setEscape($options['escape']);
}
/*
* Add headers
*/
if ($options['firstRowTitles']) {
$headers = $columns;
$csv->insertOne($headers);
}
/*
* Add records
*/
foreach ($data as $key => $item) {
$csv->insertOne([$key, $item]);
}
/*
* Output
*/
if ($options['useOutput']) {
$csv->output($options['fileName']);
}
/*
* Save for download
*/
$csvName = uniqid('oc');
$csvPath = temp_path().'/'.$csvName;
$output = $csv->__toString();
File::put($csvPath, $output);
$headers = Response::download($csvPath, 'export.csv')->headers->all();
$result = Response::make(File::get($csvPath), 200, $headers);
return $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment