如何从PHP中获取AWS S3中的资源?

时间:2017-08-25 16:52:31

标签: php amazon-s3

AWS S3 documentation非常明确和直截了当:

<?php

// Include the AWS SDK using the Composer autoloader.
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';

// Instantiate the client.
$s3 = S3Client::factory();

try {
    // Get the object
    $result = $s3->getObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname
    ));

    // Display the object in the browser
    header("Content-Type: {$result['ContentType']}");
    echo $result['Body'];
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

这强烈暗示$result['Body']是文件的实际内容(在我的例子中是JSON文档)。但是,如果我print_r($result['Body']),我会得到一个Guzzle对象:

Guzzle\Http\EntityBody Object
(
    [contentEncoding:protected] => 
    [rewindFunction:protected] => 
    [stream:protected] => Resource id #9
    [size:protected] => 
    [cache:protected] => Array
        (
            [wrapper_type] => PHP
            [stream_type] => TEMP
            [mode] => w+b
            [unread_bytes] => 0
            [seekable] => 1
            [uri] => php://temp
            [is_local] => 1
            [is_readable] => 1
            [is_writable] => 1
        )

    [customData:protected] => Array
        (
            [default] => 1
        )

)

如何检索文件的实际内容?

composer.json

{
  "require": {
    "aws/aws-sdk-php": "2.*",
    "guzzle/guzzle": "3.9.3",
  }
}

1 个答案:

答案 0 :(得分:1)

Guzzle EntityBody类可以转换为字符串来获取实际响应,所以在你的情况下

$response = (string) $result['Body'];

为了清楚一点 - 示例的工作原理是,在调用echo时,以下变量(或语句)会自动转换为字符串。在调用print_r时,您会获得更详细的对象视图,其中可能包含或不包含您正在寻找的字符串。