Skip to content

Instantly share code, notes, and snippets.

@macghriogair
Created March 20, 2016 14:23
Show Gist options
  • Save macghriogair/7909f5c24f8c742ce2e6 to your computer and use it in GitHub Desktop.
Save macghriogair/7909f5c24f8c742ce2e6 to your computer and use it in GitHub Desktop.
stream csv file lumen
<?php
namespace App\Http\Controllers;
use App\Result;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ExportController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
}
public function index()
{
$results = Result::all()->toArray();
$headers = $this->getFileResponseHeaders('export.csv');
return $this->streamFile(function () use ($results) {
$output = fopen('php://output', 'w');
foreach ($results as $row) {
fputcsv($output, $row);
}
fclose($output);
}, $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-type' => 'text/csv',
'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