AWS S3如何在不下载PHP

时间:2017-01-31 04:00:08

标签: php amazon-web-services amazon-s3

我的S3包含其中包含JSON的.gz对象。我只是想访问这个JSON而不实际将对象下载到文件中。

$iterator = $client->getIterator('ListObjects', array(
    'Bucket' => $bucket
));

foreach ($iterator as $object) {
    $object = $object['Key'];

    $result = $client->getObject(array(
        'Bucket' => $bucket,
        'Key'    => $object
    ));

    echo $result['Body'] . "\n";
}

当我在shell中运行上面的内容时,它会在echo行上输出乱码。简单地检索.gz对象的内容并保存到变量的正确方法是什么?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以像这样使用stream wrapper

$client->registerStreamWrapper();

if ($stream = fopen('s3://bucket/key.gz', 'r')) {
    // While the stream is still open
    while (!feof($stream)) {
        // Read 1024 bytes from the stream
        $d = fread($stream, 1024);
        echo zlib_decode($d);
    }
    // Be sure to close the stream resource when you're done with it
    fclose($stream);
}

如果您要将其发送到浏览器,则不需要对其进行zlib_decode,只需设置标题:

header('Content-Encoding: gzip');