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/