Created
October 21, 2017 18:54
-
-
Save LukeTowers/8b239f820150a8d2f35a17edb0e06c0a to your computer and use it in GitHub Desktop.
October
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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