【问题标题】:Invalid JSON Payload Google Sheets API Appending fields无效的 JSON 有效负载 Google Sheets API 附加字段
【发布时间】: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


    【解决方案1】:

    所以最后是几件事。

    首先,我尝试传递 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);
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2023-04-03
      • 1970-01-01
      • 2016-06-19
      相关资源
      最近更新 更多