Skip to content

Instantly share code, notes, and snippets.

@guiguiboy
Last active April 4, 2023 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guiguiboy/fbc237e8bca83a88f50f85512496197d to your computer and use it in GitHub Desktop.
Save guiguiboy/fbc237e8bca83a88f50f85512496197d to your computer and use it in GitHub Desktop.
Export large files using Symfony StreamedResponse and prevent memory limit issues
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ExportController extends AbstractController
{
/**
* @Route("/export",name="export_route")
*/
public function exportAction()
{
$handle = fopen('../my_large_file.csv', 'r');
//$handle can also be read from php://temp if you need to create the file in the same action
//in that case, do not forget to rewind($handle) after writing
$callback = function () use ($handle) {
fpassthru($handle);
fclose($handle);
};
$response = new StreamedResponse($callback, 200);
//set the headers to whatever you wish
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', "attachment; filename=export.csv");
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment