想要添加新的记录/行在谷歌电子表格中的PHP


Want to add new record/row in Google spreadsheet in PHP

我想通过php编码在谷歌电子表格中添加新记录。我已经搜索并找到了一个解决方案,即使用gmail id和密码系统进行身份验证。它最初是工作的,但2天后它突然停止工作。代码如下所述:

<?php
include 'spreadsheet.php';
$Spreadsheet = new Spreadsheet("xxxxx@gmail.com", "xxxxxxx");
$Spreadsheet->setSpreadsheet("Tester")->setWorksheet("Sheet1")->add(array("First Name" => "Cell 1", "Last Name" => "Cell 2"));
?>

在它停止工作后,我才知道谷歌已经改变了它的登录系统,我需要迁移到Oauth系统进行认证。

在做了很长的R &D我发现了一个例子——"https://github.com/asimlqt/php-google-spreadsheet-client"。但是它不起作用,在梳理了我的各种搜索源之后,我开发了以下代码:

<?php
include_once "google-api-php-client/examples/templates/base.php";
/************************************************
  Make an API request authenticated with a service
  account.
 ************************************************/
require_once realpath(dirname(__FILE__) . '/google-api-php-client/src/Google/autoload.php');
$accessToken = getGoogleTokenFromKeyFile("XXXXXXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXX");
use Google'Spreadsheet'DefaultServiceRequest;
use Google'Spreadsheet'ServiceRequestFactory;
//ServiceRequestFactory::setInstance(new DefaultServiceRequest($accessToken));
// Load spreadsheet and worksheet
$worksheet = (new Google'Spreadsheet'SpreadsheetService())
    ->getSpreadsheets()
    ->getByTitle('Sheet1')       // Spreadsheet name
    ->getWorksheets()
    ->getByTitle('Tester');      // Worksheet name
$listFeed = $worksheet->getListFeed();
// Uncomment this to find out what Google calls your column names
// print_r($listFeed->getEntries()[0]->getValues());
// Add a new blank row to the spreadsheet, using the column headings
$listFeed->insert(['name' => 'Simon', 'age' => 25, 'gender' => 'male']);
/**
 * Retrieves a Google API access token by using a P12 key file,
 * client ID and email address
 *
 * These three things may be obtained from 
 * https://console.developers.google.com/
 * by creating a new "Service account"
 */
function getGoogleTokenFromKeyFile($clientId, $clientEmail, $pathToP12File) {
    $client = new Google_Client();
    $client->setClientId($clientId);
    $cred = new Google_Auth_AssertionCredentials(
        $clientEmail,
        array('https://spreadsheets.google.com/feeds'),
        file_get_contents($pathToP12File)
    );
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $service_token = json_decode($client->getAccessToken());
    return $service_token->access_token;
}

?>

但不幸的是,这个也不工作,在突然的时间框架后,它显示请求超时错误在我的本地xampp服务器。

到目前为止,我的申请被搁置了。真的不知道现在该怎么办。如果有人对此有任何具体的解决办法,请与我分享。我的主要目的是当用户在我的网站上提交他的详细信息时,向谷歌电子表格添加数据。或者如果在谷歌更改身份验证系统后不可能,请也确认我。我想找到一个解决这个问题的最终办法。

提前感谢。

如果您能够检索到一个有效的令牌,那么在请求头中使用"Bearer yourtokenstring"传递令牌。谷歌最近从"googleloginauth =yourtokenstring"改变了这一点。请使用不记名者标签。

如果您正在努力检索有效的访问令牌,请考虑使用带有p12密钥文件的服务帐户。向服务帐户电子邮件地址授予电子表格的编辑权限。