-
-
Save brianyoungblood/cbfa6efdc8eb372b405fdfcdcdc73c00 to your computer and use it in GitHub Desktop.
Google Drive PHP API library example to download a spreadsheet file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 protected]'); | |
$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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment