Last active
November 23, 2020 09:00
-
-
Save waqashassan98/6dc2e48e762aa02d1e4ce92d7e6be22b to your computer and use it in GitHub Desktop.
Access Google Sheets via API in PHP, using Server to Server OAUTH
This file contains 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 | |
$root_path = '/path/to/your/root/'; | |
require_once($root_path.'vendor/autoload.php'); | |
define('APPLICATION_NAME', 'Google Sheets Importer'); | |
define('APP_CREDENTIALS_PATH', $root_path.'service-account-2fb0dd3da332.json');// The Json file's path that you received via service account | |
define('SCOPES', | |
implode(' ', | |
array( | |
Google_Service_Sheets::SPREADSHEETS_READONLY | |
) | |
) | |
); | |
$client = getClient(); | |
$service = new Google_Service_Sheets($client); | |
$spreadsheetId = 'Hash of Your Spread Sheet ID'; | |
$range ="sheet1";//title of the working sheet tab | |
//Reading | |
$response = $service->spreadsheets_values->get($spreadsheetId, $range); | |
$values = $response->getValues(); | |
if (empty($values)) { | |
print "No data found.\n"; | |
} else { | |
echo "<pre>"; | |
var_dump($values); | |
echo "</pre>"; | |
} | |
//Writing | |
$values = [ | |
[ | |
// Cell values ... | |
"updated" | |
], | |
// Additional rows ... | |
]; | |
$body = new Google_Service_Sheets_ValueRange([ | |
'values' => $values | |
]); | |
$params = [ | |
'valueInputOption' => 'USER_ENTERED' | |
]; | |
$result = $service->spreadsheets_values->update($spreadsheetId, "B1", $body, $params); | |
printf("%d cells updated.", $result->getUpdatedCells()); | |
function getClient() { | |
$client = new Google_Client(); | |
if ($credentials_file = checkServiceAccountCredentialsFile()) { | |
// set the location manually | |
$client->setAuthConfig($credentials_file); | |
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) { | |
// use the application default credentials | |
$client->useApplicationDefaultCredentials(); | |
} else { | |
//echo "Missing Credentials"; | |
return false; | |
} | |
$client->setApplicationName(APPLICATION_NAME); | |
$client->setScopes(SCOPES); | |
return $client; | |
} | |
function checkServiceAccountCredentialsFile() | |
{ | |
// service account creds | |
$application_creds = APP_CREDENTIALS_PATH; | |
return file_exists($application_creds) ? $application_creds : false; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment