Google Drive API v3 - downloading files in PHP

房东的猫 提交于 2019-12-03 03:26:59

I figured it out after a bit of experimenting.

When you call the get() method with the alt=>media parameter as specified in the docs you get the underlying HTTP response which is a Guzzle response object (as apparently the client library uses Guzzle for it's underlying transport).

From there you can call any Guzzle response method such as $response->getStatusCode() or you can get a stream of the actual file content.

Would have been helpful if they had documented this somewhere!

EDIT: Here's a rough example if anyone else gets stuck of how to save a file.

<?php

date_default_timezone_set("Europe/London");
require_once 'vendor/autoload.php';

// I'm using a service account, use whatever Google auth flow for your type of account.

putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json');
$client = new Google_Client();
$client->addScope(Google_Service_Drive::DRIVE);
$client->useApplicationDefaultCredentials();

$service = new Google_Service_Drive($client);

$fileId = "0Bxxxxxxxxxxxxxxxxxxxx"; // Google File ID
$content = $service->files->get($fileId, array("alt" => "media"));

// Open file handle for output.

$outHandle = fopen("/path/to/destination", "w+");

// Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle.

while (!$content->getBody()->eof()) {
        fwrite($outHandle, $content->getBody()->read(1024));
}

// Close output file handle.

fclose($outHandle);
echo "Done.\n"

?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!