-
-
Save mosufy/24fac213673a571358c4 to your computer and use it in GitHub Desktop.
Returns response for export in CSV format for laravel
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
<?php | |
/** | |
* Returns response in CSV format | |
* | |
* Call this class from Controller as below | |
* return Response::csv($data, $filename); | |
*/ | |
Response::macro('csv', function($data, $filename = 'data.csv', $status = 200, $delimiter = ",", $linebreak = "\n", $headers = array()) | |
{ | |
return Response::stream(function() use ($data, $delimiter, $linebreak) { | |
foreach ($data as $row) { | |
$keys = array(); $values = array(); | |
$i = (isset($i)) ? $i+1 : 0; | |
foreach ($row->toArray() as $k => $v) { | |
if ($i==0) $keys[] = $k; | |
$values[] = is_numeric($v) ? $v : '"' . str_replace('"', '""', $v) . '"'; | |
} | |
if (count($keys) > 0) echo implode($delimiter,$keys) . $linebreak; | |
if (count($values) > 0) echo implode($delimiter,$values) . $linebreak; | |
} | |
}, $status, array_merge(array( | |
'Content-type' => 'application/csv', | |
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', | |
'Content-Description' => 'File Transfer', | |
'Content-type' => 'text/csv', | |
'Content-Disposition' => 'attachment; filename=' . $filename, | |
'Expires' => '0', | |
'Pragma' => 'public', | |
), $headers)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment