Php Google Sheeet API的问题
我正在尝试使用PHP将web服务写入GoogleSheet API 为此,我遵循谷歌控制台的文档 并制作以下代码Php Google Sheeet API的问题,php,google-sheets,google-sheets-api,Php,Google Sheets,Google Sheets Api,我正在尝试使用PHP将web服务写入GoogleSheet API 为此,我遵循谷歌控制台的文档 并制作以下代码 <?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() { $clie
<?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
);
你能帮我做这件事吗?上面写得很清楚:
此应用程序必须在命令行上运行
因此,这意味着您不是使用命令行运行它,而是尝试使用浏览器访问它。如果你按照医生说的做:
那就行了
为什么使用浏览器访问时会出现此异常? 由于代码开头有以下几行:
if(php\u sapi\u name()!='cli'){
抛出新异常('此应用程序必须在命令行上运行');
}
如果我想在浏览器上运行它怎么办?
只需删除这些行,就可以使用浏览器运行脚本
thrown in Google_sheet/quickstart.php on line 5
php quickstart.php