How to add file from direct download URL ?
bastien70 opened this issue · 0 comments
bastien70 commented
Description of the problem
I've few .pdf links to include to a .zip archive.
The .pdf links are direct download links, so the code I found here doesn't work.
The .zip archive is generated, but with empty files in here
Example code
$response = new StreamedResponse(function () use ($invoicesLines) {
$options = new Archive();
$options->setContentType('application/octet-stream');
// this is needed to prevent issues with truncated zip files
$options->setZeroHeader(true);
//initialise zipstream with output zip filename and options.
$zip = new ZipStream('invoices.zip', $options);
foreach ($invoicesLines as $invoice) {
$fp = tmpfile();
// Download File
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_URL, $invoice->getLink());
curl_exec($ch);
// Force to write all data
fflush($fp);
// Rewind to the beginning, otherwise the stream is at the end from the start
rewind($fp);
// Add File
$zip->addFileFromStream(sprintf('%s.pdf', $invoice->getNumber()), $fp);
// Close the Temp File
fclose($fp);
}
$zip->finish();
});
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', sprintf('attachment;filename="%s"', 'invoices.zip'));
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
Informations
- ZipStream-PHP version: 2.1.0
- PHP version: 8.0