无效的JSON有效载荷Google Sheets API附加字段



,所以我要做的是在Google表上获取一系列单元格的值。

我已经成功地做到了。

然后,使用值数组,我向我们的CRM系统提出了另一个API请求,该请求也使我返回了一组结果。从我们的CRM系统返回给我的结果集,我想更新与阅读值不同范围内的单元格。一切都在同一Google表上。

但是,在尝试附加字段时,我似乎会遇到错误。

"接收到无效的JSON有效载荷。未知名" 0 " at data.values [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%sn", $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数组的事实吗?它是否需要我只是不知道的特定格式,而且我似乎无法在文档中找到正确的答案,因为似乎您可以在附加多个值时将其传递为一个数组。

预先感谢!

,最终是几件事。

首先,我试图通过和XML对象并将其转换为PHP数组。Sheets API不喜欢这样,所以我必须创建这样的数组。不是最漂亮的,但它起作用

$companyBalance[] = sprintf("%s",$xmlresult->balance);

这使我能够创建一个由字符串组成的阵列。

然后,由于我正在动态地构建此数组,因此我使用一个用于循环访问数组的每个部分并单独更新单元格。同样不是最优雅的解决方案,但我只是没有时间回去并立即更改它。但是,这可能会帮助需要指向正确方向的人。

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

最新更新