Last active
April 4, 2023 12:36
-
-
Save guiguiboy/fbc237e8bca83a88f50f85512496197d to your computer and use it in GitHub Desktop.
Export large files using Symfony StreamedResponse and prevent memory limit issues
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 | |
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