1

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]);
    }
}


?>
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Dcoder
  • 27
  • 6

2 Answers2

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);
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • I tried this but it is showing many more errors. In this '$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']); ' will there be something else in the URL section or the same URL which you have given ? – Dcoder Feb 21 '22 at 05:02
  • That is not a url that is a scope. What is the other error update your question with the one you tried. and the error. – Linda Lawton - DaImTo Feb 21 '22 at 07:19
0

Update this code:

$client->setScopes(\Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);

to this:

$client->setScopes(Google\Service\Sheets::SPREADSHEETS);
$service = new Google\Service\Sheets($client);