Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download (stream) large files in symfony2

What I want to do :
User hit a url (ex: BASE-URL/download/json).
Code fetch huge data from database and stream it into a JSON file and user is prompted to download that file.

What I tried :
Created a large (700 MB) JSON file. Tried opening it with code, but error was thrown.

file_get_contents($file)

Error :

Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)

I am working in Symfony2. Data can be upto 700MB in size. Can't increase the allocated memory. How can I achieve this? Please comment if any further information is required.

like image 202
Anurag Rana Avatar asked Sep 29 '15 08:09

Anurag Rana


1 Answers

I was able to achieve what I wanted with the help of all the above comments.
Here is the code for the same.

$response = new StreamedResponse();  
$i = -999999;  
$response->setCallback(function () {  
    while($i < 999999){  
        echo '{"G1ello":"hualala"}';  
        $i = $i + 1;  
    }  
});  
$filename = "Data.json";  
$contentDisposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Content-Disposition', $contentDisposition);
return $response;

It created a large file which I was able to download. Exactly what I wanted. Posting the solution so that it can help someone with same issue.

like image 162
Anurag Rana Avatar answered Sep 17 '22 22:09

Anurag Rana