Skip to content

Instantly share code, notes, and snippets.

@geschke
Created April 21, 2014 17:15
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save geschke/11149268 to your computer and use it in GitHub Desktop.
Google Drive PHP API library example to download a spreadsheet file
<?php
require_once __DIR__ . '/vendor/autoload.php';
class DriveFile
{
private $service = null;
private $client = null;
private $auth;
private $serviceEmail = '';
private $serviceKeyFilename = '';
private $userEmail = '';
/**
* Constructor, initialize with service email and name of private key file.
*
* @param string $serviceEmail
* @param string $serviceKeyFilename
* @param string $userEmail
*/
public function __construct($serviceEmail = '', $serviceKeyFilename = '', $userEmail='')
{
$this->serviceEmail = $serviceEmail;
$this->serviceKeyFilename = $serviceKeyFilename;
$this->userEmail = $userEmail;
}
/**
* Build Drive API authenticatioin and access service.
* We assume that nothing will go wrong.
*/
public function buildService()
{
$key = file_get_contents($this->serviceKeyFilename);
$this->auth = new Google_Auth_AssertionCredentials(
$this->serviceEmail,
array('https://www.googleapis.com/auth/drive'),
$key);
$this->auth->sub = $this->userEmail;
$this->client = new Google_Client();
$this->client->setAssertionCredentials($this->auth);
$this->service = new Google_Service_Drive($this->client);
}
/**
* Search for file by title and retrieve a list of File resources.
*
* @param string $title
* @return Array List of Google_DriveFile resources.
*/
public function searchFile($title='')
{
if (!$this->service) {
$this->buildService();
}
$query = "title='" . $title . "'";
$result = array();
$pageToken = null;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
if ($query) {
$parameters['q'] = $query;
}
$files = $this->service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = null;
}
} while ($pageToken);
return $result;
}
/**
* Returns meta data by file id
*
* @param Google_Service_Drive_DriveFile file object to print metadata for.
* @return array of meta data
*/
public function getMetadata(Google_Service_Drive_DriveFile $file)
{
try {
return array('title' => $file->getTitle(),
'description' => $file->getDescription(),
'mime_type' => $file->getMimeType()
);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
/**
* Return downloaded file by file object and mime type
*
* @param File $file Drive File instance.
* @return String The file's content if successful, null otherwise.
* @param string $fileMimeType, default spreadsheet as example
*/
public function getFile(Google_Service_Drive_DriveFile $file, $fileMimeType='')
{
if (!$this->service) {
$this->buildService();
}
$downloadUrl = $file->getExportLinks()[$fileMimeType];
if ($downloadUrl) {
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
// use authentication parameter to login with previously created credentials
// and request the file
$client = new Google_Client();
$client->setAssertionCredentials($this->auth);
$client->getAuth()->sign($request);
$io = $client->getIo();
$httpRequest = $io->makeRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred. Maybe throw some exception?
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
/**
* Shortcut method for getting spreadsheet file content
*
* @param Google_Service_Drive_DriveFile $file
* @return String
*/
public function getSpreadsheetFile(Google_Service_Drive_DriveFile $file)
{
return $this->getFile( $file, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
}
}
// example client code
$driveFile = new DriveFile('<your-access-address_will_be_created_by_google>@developer.gserviceaccount.com',
__DIR__ . '/google-privatekey.p12',
'<email-address-with-appropriate-rights@example.com');
$files = $driveFile->searchFile('my-spreadsheet-title');
if (isset($files[0])) {
$file = $files[0];
echo "file id: " . $file->id . "\n";
$meta = $driveFile->getMetadata( $file);
echo "meta data: \n";
print_r($meta);
if ($content = $driveFile->getSpreadsheetFile($file)) {
file_put_contents('spreadsheet.xlsx',$content);
}
else {
echo "An error occurred.";
}
}
echo "\n";
@CBRAG11
Copy link

CBRAG11 commented Apr 25, 2018

What values need to be passed in serviceEmail, serviceKeyFilename, userEmail?
From where do i fetch these?

@Tejpalsb
Copy link

Tejpalsb commented Sep 6, 2018

what is require_once DIR . '/vendor/autoload.php'; file content?

@tuananhcwrs
Copy link

e content?

For Google SDK classes that you use, example Google_Http_Request, Google_Client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment