TRiG TRiG - 1 month ago 13
PHP Question

How do I fetch a resource from AWS S3 in PHP?

The AWS S3 documentation is quite clear and straightforward:

<?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";
}


This strongly suggests that
$result['Body']
is the actual content of the file (in my case, a JSON document). However, if I do
print_r($result['Body'])
I get a Guzzle Object:

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
)

)


How can I retrieve the actual content of the file?

composer.json

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

Answer Source

Guzzle EntityBody classes can just be cast to a string to fetch the actual response, so in your case

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

For a bit of clarity — the reason the example works is that when calling echo, the following variable (or statement) is automatically cast to a string. When calling print_r instead, you get a more detailed view of the object, which may or may not include the string you're looking for.