Created
March 20, 2016 14:23
-
-
Save macghriogair/7909f5c24f8c742ce2e6 to your computer and use it in GitHub Desktop.
stream csv file lumen
This file contains hidden or 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 | |
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