php - 如何使用 PHP 从 AWS S3 获取资源?

标签 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",
  }
}

最佳答案

Guzzle EntityBody 类只需转换为字符串即可获取实际响应,因此在您的情况下

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

为了清楚起见,该示例起作用的原因是,当调用 echo 时,以下变量(或语句)会自动转换为字符串。相反,当调用 print_r 时,您将获得该对象的更详细 View ,其中可能包含也可能不包含您要查找的字符串。

关于php - 如何使用 PHP 从 AWS S3 获取资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45886177/

相关文章:

javascript - 在 laravel blade 模板里面写一个 js 表达式

c# - 使用 C# 从 s3 存储桶下载文件

amazon-s3 - 我应该将附件存储在 CouchDB 还是 S3 中?

amazon-web-services - 静态 Amazon S3 文件的 GZIP 压缩

ruby - amazon s3 上传签名 url public-read

php - 简单代理无法获取 JSON 响应

php - 打字错误3 : Add LINK tags to CSS Files in the HEAD tag from within a Typo 3 extension

javascript - PhoneGap 文件传输在上传到服务器时损坏 .mp3

php - 使用 AJAX 将数据记录到数据库

amazon-web-services - 部署到 AWS S3 与 github 同步