使用google-api-php-client

时间:2016-08-25 01:44:30

标签: php google-sheets google-api google-api-php-client

我尝试使用 google-api-php-client

定期从其他来源( MySQL 查询)转储一些数据

到特定的 Google电子表格

最终结果应该是一个php脚本,它在我的服务器的cron中运行,定期将一些数据从SQL查询转储到我的特定谷歌电子表格。

我拥有谷歌文档中的所有内容。

serviceID,Json密钥,电子表格ID,范围

我实际上能够从电子表格中读取范围

问题是......如何使用google-api-php-client在我的电子表格中写入数据?

这是我用来从电子表格中读取数据的代码。

    <?php
error_reporting(E_ALL);
ini_set("display_errors", 1); 
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__.'/google-api-php-client/src');
require_once 'Google/autoload.php';


$key = json_decode(file_get_contents('myJasonkeyFile.json'));
$service_account_email='[SERVICE_EMAIL]@myproject.iam.gserviceaccount.com';
$appName='project-name';
$scopes = array(Google_Service_Sheets::SPREADSHEETS);


            $credentials = new Google_Auth_AssertionCredentials(
                $service_account_email,    // it's the client email
                $scopes,   // it's google spreadsheet scope
                $key->private_key         // here is the private key
            );

$client = new Google_Client();
$client->setAssertionCredentials($credentials);

if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion();
}

$client->setApplicationName($appName);
$service = new Google_Service_Sheets($client);


$spreadsheetId = '984984kjldkjldkd0984lkjdlkdj[randomkey]';
$range = 'hoja1!A1:C4';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);

$values = $response->getValues();

if (count($values) == 0) {
  print "No data found.\n";
} else {
  print "Name, Major:\n";
  foreach ($values as $row) {
    // Print columns A and E, which correspond to indices 0 and 4.
    printf("%s, %s\n", $row[0], $row[2]);
  }
}

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

此代码将向电子表格添加一个包含所有信息的新行。 我在这部分中使用了JS(参见上一个函数,它是sais&#34;值:[&#34;

<script type="text/javascript">

    // Developer Console, https://console.developers.google.com
    var CLIENT_ID = '############-#########.apps.googleusercontent.com';
    var SECRET = '##################';
    var REDIRECT = 'http://#######.com';
    var AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
    var TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token';
    var SCOPES = ["https://www.googleapis.com/auth/spreadsheets"];
    var SPREADSHEET = '############';
    var LAST = 0;

    // var getCode = 'https://accounts.google.com/o/oauth2/auth?client_id='+ CLIENT_ID +'&scope='+ SCOPES +'&redirect_uri=http://localhost&response_type=code&access_type=offline';

    function checkAuth() {
        gapi.auth.authorize(
            {
                'client_id': CLIENT_ID,
                'scope': SCOPES.join(' '),
                'immediate': true
            }, handleAuthResult);
    }

    function handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
            authorizeDiv.style.display = 'none';
            loadSheetsApi();
        } else {
            authorizeDiv.style.display = 'inline';
        }
    }

    function handleAuthClick(event) {
        gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: false}, handleAuthResult);
        return false;
    }

    function loadSheetsApi() {
        var discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
        gapi.client.load(discoveryUrl).then(setData);
    }

    function setData() {
        gapi.client.sheets.spreadsheets.values.get({
            spreadsheetId: SPREADSHEET,
            range: 'Sheet1',
        }).then(function(response) {
            var range = response.result;

            if (range.values.length > 0) {
                LAST = (range.values.length + 1);
            }
        }).then(function() {
            gapi.client.sheets.spreadsheets.values.update({
                spreadsheetId: SPREADSHEET,
                valueInputOption: 'USER_ENTERED',
                values: [ ["<?php echo $name; ?>", "<?php echo $email; ?>", "<?php echo $subject; ?>", "<?php echo $category; ?>", "<?php echo $iama; ?>", "<?php echo $country; ?>", "<?php echo $message; ?>"] ],
                range: 'Sheet1!A' + window.LAST,
            }).then(function(response) {
                // console.log('update last: ' + window.LAST);
            });
        });
    }

</script>