'Uncaught Error: Undefined constant Google\Service\Sheets::spreadsheets in

I am trying to access a google sheet using Google's sheets API using PHP

I am stuck with this error !

Fatal error: Uncaught Error: Undefined constant Google\Service\Sheets::spreadsheets in {my file path} :8 Stack trace: #0 {main} thrown in {my file path} on line 8

My code

<?php

require __DIR__ . '/vendor/autoload.php';


$client = new \Google_Client();
$client->setApplicationName('Google Sheets API PHP');
$client->setScopes([\Google_Service_Sheets::spreadsheets]);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$service = new Google_Service_Sheets($client);
$spreadsheetId = "1FA--HxEEu3zp_u2Bzqhz5nEN2FHSpE5XhQNslEc8LBg";

$range = "Data Analytics - Spreadsheet example!B2:D17";
$response = $service->spreadsheets_values- 
>get($spreadsheetId,$range);
$values = $response->getvalues();

if (empty($values))
{
    echo "No data found";
}
else
{ 
    $mask = "%10s %-10s %s \n";
    foreach($values as $row)
    {
        echo sprintf($mask, $row[0], $row[1], $row[2]);
    }
}


?>


Solution 1:[1]

Try to change

$client->setScopes([\Google_Service_Sheets::spreadsheets]);

To. I find this way works better.

$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']);

The way you are doing it should work but you need to have the correct case

$client->setScopes(Google_Service_Sheets::SPREADSHEETS);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1