Google Sheeet API的问题

MNJ

我正在尝试使Web服务使用PHP写入GoogleSheet API。

为此,我正在遵循Google控制台的文档

链接

并制作以下​​代码

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

if (php_sapi_name() != 'cli') {
 throw new Exception('This application must be run on the command line.');
}

function getClient()
{
  $client = new Google_Client();
  $client->setApplicationName('Google Sheets API PHP Quickstart');
  $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
  $client->setAuthConfig('credentials.json');
  $client->setAccessType('offline');
  $client->setPrompt('select_account consent');

  $tokenPath = 'token.json';
  if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
  }

  if ($client->isAccessTokenExpired()) {
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    } 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);
        $client->setAccessToken($accessToken);

        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
  return $client;
}


$client = getClient();
$service = new Google_Service_Sheets($client);

$spreadsheetId = 'XXXX';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = [["This","is","a","new","row"],];
$body = new Google_Service_Sheets_ValueRange([
  "values" =>$values
]);
$params = [
  "valueInputOption" => "RAW",
   "insertDataOption" => "INSERT_ROWS"
];
$result = $service->spreadsheets_values->append(
  $spreadsheetId,
  $range,
  $body,
  $params
);

但是当我运行这段代码时,这给了我下面给出的错误。

[25-Nov-2019 01:53:03美国/芝加哥] PHP致命错误:未捕获的异常“ Exception”,消息为“此应用程序必须在命令行上运行”。在Google_sheet / quickstart.php中:5堆栈跟踪:

0 {main}

thrown in Google_sheet/quickstart.php on line 5

你能帮我这个忙吗

尤里

它说得很清楚:

此应用程序必须在命令行上运行。

因此,这意味着您没有使用命令行运行它,而是尝试使用浏览器访问它。如果您按照快速入门指南所述

php quickstart.php

那么它将起作用。


为什么在使用浏览器访问时看到此异常?

由于此行位于代码的开头:

if (php_sapi_name() != 'cli') {
 throw new Exception('This application must be run on the command line.');
}

如果要在浏览器上运行该怎么办?

只需删除这些行,您就可以使用浏览器运行脚本。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章