How can one optimize PHP scripts to handle larger files when creating Zip archives?
When creating Zip archives with PHP, handling larger files can lead to memory exhaustion or execution time limits being exceeded. To optimize PHP scripts for handling larger files when creating Zip archives, it is recommended to use streaming to read and write files in chunks rather than loading the entire file into memory at once.
// Create a zip archive and add files using streaming to handle larger files
$zip = new ZipArchive();
$zipFileName = 'archive.zip';
$zip->open($zipFileName, ZipArchive::CREATE);
$files = ['file1.txt', 'file2.txt', 'largefile.zip'];
foreach ($files as $file) {
$handle = fopen($file, 'rb');
if ($handle) {
while (($buffer = fread($handle, 2048)) !== false) {
$zip->addFromString(basename($file), $buffer);
}
fclose($handle);
}
}
$zip->close();
Keywords
Related Questions
- How can the issue of character encoding and displaying special characters like umlauts be addressed in PHP scripts, especially when working with Linux environments?
- How can developers ensure that the XML received from an API in PHP is valid and properly formatted before parsing it?
- What steps can be taken to troubleshoot and resolve issues with PHP database queries not returning results when special characters are involved?