Skip to content

Instantly share code, notes, and snippets.

@ahgood
Created June 6, 2018 07:59
Show Gist options
  • Save ahgood/5000e47fa629106ca67648736f6f3f29 to your computer and use it in GitHub Desktop.
Save ahgood/5000e47fa629106ca67648736f6f3f29 to your computer and use it in GitHub Desktop.
Export db data to csv
use App\MyModel;
...
use Symfony\Component\HttpFoundation\StreamedResponse;
...
public function Export() {
$results = MyModel::all()->toArray();
$headers = $this->getFileResponseHeaders('export.csv');
return $this->streamFile(function () use ($results) {
$fp = fopen('php://fp', 'w');
fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
$csv_fields = array();
$csv_fields[] = '标题 1';
$csv_fields[] = 'Header 2';
$csv_fields[] = 'Header 3';
$csv_fields[] = 'Header 4';
fputcsv($fp, $csv_fields);
foreach ($results as $row) {
fputcsv($fp, $row);
}
fclose($fp);
}, $headers);
}
protected function streamFile($callback, $headers) {
$response = new StreamedResponse($callback, 200, $headers);
$response->send();
}
protected function getFileResponseHeaders($filename) {
return [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Encoding' => 'UTF-8',
'Content-type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename=' . $filename,
'Expires' => '0',
'Pragma' => 'public'
];
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment