Stream ZIP data to a callback function using CallbackStreamWrapper
mainThe ZipStream\Stream\CallbackStreamWrapper::open() method allows you to intercept the ZIP data stream via a callback function. This is useful for:
- Streaming to multiple destinations simultaneously (e.g., echoing to the browser while writing to a file).
- Progress tracking by monitoring the length of the
$datachunks. - Custom logging or data transformation.
Note: When using a custom outputStream via a callback, you should set sendHttpHeaders: false in the ZipStream constructor to prevent the library from automatically sending HTTP headers, as you are now manually controlling the output flow.
Important Recommendation: For data transformations (like encoding), prefer using PHP's built-in stream filters via stream_filter_append() rather than performing transformations inside the callback. Stream filters are more efficient and maintain better data integrity.
use ZipStream\ZipStream;
use ZipStream\Stream\CallbackStreamWrapper;
// Example: Stream to multiple destinations
$backupFile = fopen('backup.zip', 'wb');
$logFile = fopen('transfer.log', 'ab');
$zip = new ZipStream(
outputStream: CallbackStreamWrapper::open(function (string $data) use ($backupFile, $logFile) {
// Send to browser
echo $data;
// Save to file efficiently
fwrite($backupFile, $data);
// Log transfer progress
fwrite($logFile, "Transferred " . strlen($data) . " bytes\n");
}),
sendHttpHeaders: false,
);
$zip->addFile('hello.txt', 'Hello World!');
$zip->finish();
fclose($backupFile);
fclose($logFile);