2017-08-25 16 views
1

AWS S3 documentation是很清楚明瞭:如何從PHP中的AWS S3獲取資源?

<?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\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", 
    } 
} 
+0

我覺得我錯過了一些愚蠢簡單的東西。 – TRiG

回答

0

狂飲EntityBody類可以直接被轉換爲字符串,以獲取實際的響應,所以你的情況

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

對於位清晰的 - 的原因示例工作是,當調用echo時,以下變量(或語句)將自動轉換爲字符串。當調用print_r來代替時,您會看到對象的更詳細視圖,該對象可能包含或不包含要查找的字符串。