我正在检查用于从 S3 压缩流内容的良好解决方案,我遇到了ZipStream-PHP API,它已被s3-bucket-stream-zip-php API 使用,但是我猜在核心 PHP 类ZipArchive的帮助下,它的函数ZipArchive::addFromString我们可以实现相同的。
我的查询是 ZipStream-PHP API 是比 ZipArchive 更好的解决方案,用于从 S3 或任何其他云服务压缩流内容?
我正在检查用于从 S3 压缩流内容的良好解决方案,我遇到了ZipStream-PHP API,它已被s3-bucket-stream-zip-php API 使用,但是我猜在核心 PHP 类ZipArchive的帮助下,它的函数ZipArchive::addFromString我们可以实现相同的。
我的查询是 ZipStream-PHP API 是比 ZipArchive 更好的解决方案,用于从 S3 或任何其他云服务压缩流内容?
根据我的经验,最好的解决方案是使用 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