【发布时间】:2019-08-04 07:38:46
【问题描述】:
所以我要做的是获取谷歌表格上一系列单元格的值。
我已经成功地做到了。
然后,我使用值数组向我们的 CRM 系统发出另一个 API 请求,该请求也返回给我一组结果。从我们的 CRM 系统返回给我的一组结果我想更新与我读取值不同的范围内的单元格。这一切都在同一个谷歌表上。
但是,我在尝试附加字段时似乎遇到了错误。
“收到无效的 JSON 负载。‘data.values[0]’处的未知名称 \"0\"
我在我创建的数组上运行一个 foreach 循环,只是简单地打印出我需要的值,所以我知道它不是一个空数组,实际上确实包含我所追求的数据。那我错过了什么?
这是我目前正在使用的代码。
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(array(
Google_Service_Slides::PRESENTATIONS,
Google_Service_Slides::DRIVE,
Google_Service_Slides::DRIVE_FILE,
Google_Service_Slides::SPREADSHEETS)
);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = '1UOfOdjGTWXir4pGNKtb7MRJSnFlJvOqr_CBZtkQUGxA';
$range = 'COMPANY FORMULAS - MARKETING!B2:B36';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
print "No data found.\n";
} else {
foreach ($values as $row) {
//creating XML to pass to FLG
$xmldata = '<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
<key>zW0vRSn2EXqMIwklG0IeJ8g2GUCp2Pfg</key>
<request>read</request>
<id>'.$row[0].'</id>
</data>';
//using curl to send XML data to FLG via API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://watts.flg360.co.uk/api/APIPartner.php" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$returnedresult=curl_exec ($ch);
$xmlresult = simplexml_load_string($returnedresult);
$companyBalance[] = $xmlresult->balance;
}
//var_dump($companyBalance);
foreach ($companyBalance as $row) {
echo $row . "\n";
}
$spreadsheetId = '1UOfOdjGTWXir4pGNKtb7MRJSnFlJvOqr_CBZtkQUGxA';
$range = 'COMPANY FORMULAS - MARKETING!D2:D36';
$body = new Google_Service_Sheets_ValueRange([
'values' => $companyBalance
]);
$result = $service->spreadsheets_values->append($spreadsheetId, $range,
$body);
printf("%d cells appended.", $result->getUpdates()->getUpdatedCells());
}
所以基本上它只是附加似乎不起作用的单元格。它是我传递数组的格式吗?是不是我没有将它定义为 JSON 数组?它是否需要我不知道的特定格式,并且我似乎无法在文档中找到正确的答案,因为看起来您可以在附加多个值时将其传递给数组。
提前致谢!
【问题讨论】:
标签: php api google-sheets google-sheets-api