所以我想做的就是获取Google工作表中一系列单元格的值。
我已经成功地做到了。
然后使用值数组,我向CRM系统提出了另一个API请求,该请求也返回了一组结果。从我们的CRM系统返回给我的结果集,我想在与读取值不同的范围内更新单元格。全部都在同一个Google工作表上。
但是,尝试附加字段时,我似乎遇到了错误。
“接收到无效的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数组的事实吗?它是否需要我不知道的特定格式,并且在文档中似乎找不到正确的答案,因为似乎可以在添加多个值时将其传递给数组。
谢谢!
答案 0 :(得分:0)
所以最后有两件事。
首先,我尝试传递XML对象并将其转换为PHP数组。 Sheets API不喜欢这样,所以为了解决这个问题,我不得不创建这样的数组。不是最漂亮,但可以正常工作
$companyBalance[] = sprintf("%s",$xmlresult->balance);
这使我可以创建一个由字符串组成的数组。
然后,因为我是动态构建此数组,所以我使用了for循环来访问数组的每个部分并分别更新单元格。同样,这不是最优雅的解决方案,但我只是没有时间回过头来立即进行更改。但是,这可能会帮助需要指出正确方向的人。
for ($x = 0; $x <= 36; $x++) {
$y = $x + 2;
$values = [[$companyBalance[$x]]];
$options = array('valueInputOption' => 'RAW');
$body = new Google_Service_Sheets_ValueRange(['values' => $values]);
$result = $service->spreadsheets_values->update('SHEET_ID', 'COMPANY FORMULAS - MARKETING!D'.$y.':D'.$y.'', $body, $options);
print($result->updatedRange. PHP_EOL);
}