Here is my working example for "rename sheet in spreadsheet by sheetId" function.
You can use other methods from Google Spreadsheets API Docs in the same way. Hope it will be helpful for somebody
<?php
function getClient() //standard auth function for google sheets API
{
$clientConfigPath = __DIR__ . '/google_credentials/client_secret.json';
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig($clientConfigPath);
$client->setAccessType('offline');
$credentialsPath = (__DIR__ . '/google_credentials/credentials.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
function renameSheet(string $sheetId, string $newTitle, string $spreadsheetId)
{
$client = getClient();
$service = new Google_Service_Sheets($client);
$requests = [
new Google_Service_Sheets_Request([
'updateSheetProperties' => [
'properties' => [
'sheetId' => $sheetId,
'title' => $newTitle,
],
'fields' => 'title'
]
])
];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests
]);
return $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
}
UPDATE
If you want to get sheet title by sheetId, you can use following function
function getSpreadsheetInfo($spreadsheetId)
{
$client = getClient();
$service = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
return $response;
}
function getSheets($spreadsheetId)
{
$spreadsheet_info = getSpreadsheetInfo($spreadsheetId);
$sheets_info = [];
foreach ($spreadsheet_info as $item) {
$sheet_id = $item['properties']['sheetId'];
$sheet_title = $item['properties']['title'];
$sheets_info[$sheet_id] = $sheet_title;
}
return $sheets_info;
}
$sheets_info_array = getSheets($YOUR_SPREADSHEET_ID_HERE);
$sheets_info_array will be equal
array (
"sheet_id1(int)" => 'sheet_title1',
"sheet_id2(int)" => 'sheet_title3',
)
so you can get $your_sheet_id's title as $sheets_info_array[$your_sheet_id]