So what I am trying to do is get the values of a range of cells on a google sheet.
I have successfully managed to do that.
Then with the array of values I make another API request to our CRM system that too returns me a set of results. The set of results that are returned to me from our CRM system I want to update the cells in a different range from where I read the values. It's all on the same google sheet.
However I seem to encounter an error when attempting to append the fields.
"Invalid JSON payload received. Unknown name \"0\" at 'data.values[0]'
I am running a foreach loop on the array I created just simply printing out the values I need so I know it is not an empty array and in fact does contain the data I am after. So what is it I am missing?
This is the code I am working with so far.
<?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:
%s
", $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.
";
} 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 . "
";
}
$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());
}
So basically it is just appending the cells that doesn't seem to be working. Is it the format in which I am passing the array across? Is it the fact I haven't defined it to be a JSON array? Does it require a specific format I just don't know and I can't seem to find the right answer in the documentation as it just seems you can pass it an array when appending multiple values.
Thanks in advance!