|
|
|
<?php |
|
require __DIR__ . '/vendor/autoload.php'; |
|
|
|
$spreadsheetId = "8dsdfR0ucPAE_SEWQ4G_1KpzhnfSCqn6mdfdfqdfQGirs"; |
|
$applicationName = "gsheets"; |
|
$newRow = ["Hello", "World", "it's", "a", "new", "row"]; |
|
|
|
/** |
|
* Retrieves a client for Google Service Sheets |
|
* |
|
* @param string appName |
|
* @return Google_Service_Sheets |
|
*/ |
|
function getClient($appName){ |
|
$client = new Google_Client(); |
|
$client->setApplicationName($appName); |
|
$client->setScopes(Google_Service_Sheets::SPREADSHEETS); |
|
$client->setAccessType('offline'); |
|
$client->setAuthConfig(__DIR__.'/credentials.json'); |
|
return new Google_Service_Sheets($client); |
|
} |
|
|
|
/** |
|
* Inspired by https://gist.github.com/thehelvetian/2e94d60b796735b167dfb1c7560049ae |
|
* |
|
* @param Google_Service_Sheets $sheetsService |
|
* @param string $spreadsheetId |
|
* @param int $sheetId |
|
* @param array $newValues An array containing the cell values |
|
* @return bool Request status |
|
*/ |
|
function addRowToSpreadsheet($sheetsService, $spreadsheetId, $sheetId, $newValues = []) { |
|
// Build the CellData array |
|
$values = []; |
|
foreach ($newValues AS $d) { |
|
$cellData = new Google_Service_Sheets_CellData(); |
|
$value = new Google_Service_Sheets_ExtendedValue(); |
|
$value->setStringValue($d); |
|
$cellData->setUserEnteredValue($value); |
|
$values[] = $cellData; |
|
} |
|
// Build the RowData |
|
$rowData = new Google_Service_Sheets_RowData(); |
|
$rowData->setValues($values); |
|
// Prepare the request |
|
$append_request = new Google_Service_Sheets_AppendCellsRequest(); |
|
$append_request->setSheetId($sheetId); |
|
$append_request->setRows($rowData); |
|
$append_request->setFields('userEnteredValue'); |
|
// Set the request |
|
$request = new Google_Service_Sheets_Request(); |
|
$request->setAppendCells($append_request); |
|
// Add the request to the requests array |
|
$requests = array(); |
|
$requests[] = $request; |
|
// Prepare the update |
|
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array( |
|
'requests' => $requests |
|
)); |
|
|
|
try { |
|
// Execute the request |
|
$response = $sheetsService->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest); |
|
if ($response->valid()) { |
|
return true;// Success, the row has been added |
|
} |
|
} catch (Exception $e) { |
|
error_log($e->getMessage());// Something went wrong |
|
} |
|
|
|
return false; |
|
} |
|
|
|
// START APPLICATION |
|
addRowToSpreadsheet( |
|
getClient($applicationName), $spreadsheetId, 0, $newRow |
|
); |
The credentials.json file must be replaced with the generated file at Console Developers