gpt4 book ai didi

google-drive-api - 如何使用 PHP API 更新 Google 电子表格单元格

转载 作者:行者123 更新时间:2023-12-04 05:36:29 24 4
gpt4 key购买 nike

我想知道如何使用 PHP 与 Google 电子表格进行交互。

我已经浏览了 Google 文档的许多页面,但是,这些都不是我想要的。

我的目标是能够使用 oAuth(而不是电子邮件/通行证)更改单元格的内容。

如果这是 RTFM 问题,请原谅我,但我确实花了超过 2 周的时间来解决这个问题,但没有结果。 :/

最佳答案

你可以用 来做到这一点asimlqt/php-google-spreadsheet-client 图书馆。

  • 通过 composer 安装库:
    "require": {
    "asimlqt/php-google-spreadsheet-client": "dev-master"
    }
  • PHP 文件中的 Bootstrap Composer:
    require('vendor/autoload.php');
  • 按照以下步骤获取 Google API 客户端 ID、客户端电子邮件和 P12 访问 key ,如下所述:
    https://github.com/asimlqt/php-google-spreadsheet-client/wiki/How-to-use-%22Service-account%22-authorization-(rather-than-user-based-access-refresh-tokens)
  • 使用以下代码:

    $accessToken = getGoogleTokenFromKeyFile(CLIENT_ID_HERE, CLIENT_EMAIL_HERE, P12_FILE_PATH_HERE);
    use Google\Spreadsheet\DefaultServiceRequest;
    use Google\Spreadsheet\ServiceRequestFactory;
    ServiceRequestFactory::setInstance(new DefaultServiceRequest($accessToken));

    // Load spreadsheet and worksheet
    $worksheet = (new Google\Spreadsheet\SpreadsheetService())
    ->getSpreadsheets()
    ->getByTitle('xxxxxxxxx') // Spreadsheet name
    ->getWorksheets()
    ->getByTitle('xxxxxxxxx'); // 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;
    }
  • 关于google-drive-api - 如何使用 PHP API 更新 Google 电子表格单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362703/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com