根据我的经验,最好的解决方案是使用aws-sdk-php通过启用了registerStreamWrapper()的s3client访问S3上的对象。然后使用fopen从S3流式传输对象并将该流直接提供给ZipStream的addFileFromStream()函数,并让ZipStream从那里获取它。没有ZipArchive,没有大量内存开销,没有在服务器上创建zip或从Web服务器上的S3复制文件以随后用于流式传输zip。
所以:
//...
$s3Client->registerStreamWrapper(); //required
//test files on s3
$s3keys = array(
"ziptestfolder/file1.txt",
"ziptestfolder/file2.txt"
);
// Define suitable options for ZipStream Archive.
$opt = array(
'comment' => 'test zip file.',
'content_type' => 'application/octet-stream'
);
//initialise zipstream with output zip filename and options.
$zip = new ZipStream\ZipStream('test.zip', $opt);
//loop keys useful for multiple files
foreach ($s3keys as $key) {
// Get the file name in S3 key so we can save it to the zip
//file using the same name.
$fileName = basename($key);
//concatenate s3path.
$bucket = 'bucketname';
$s3path = "s3://" . $bucket . "/" . $key;
//addFileFromStream
if ($streamRead = fopen($s3path, 'r')) {
$zip->addFileFromStream($fileName, $streamRead);
} else {
die('Could not open stream for reading');
}
}
$zip->finish();如果您在Symfony控制器操作中使用ZipStream,请参阅此答案:https://stackoverflow.com/a/44706446/136151