test.php 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. require_once __DIR__ . '/vendor/autoload.php';
  3. define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
  4. define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
  5. define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
  6. // If modifying these scopes, delete your previously saved credentials
  7. // at ~/.credentials/sheets.googleapis.com-php-quickstart.json
  8. define('SCOPES', implode(' ', array(
  9. Google_Service_Sheets::SPREADSHEETS_READONLY)
  10. ));
  11. if (php_sapi_name() != 'cli') {
  12. throw new Exception('This application must be run on the command line.');
  13. }
  14. /**
  15. * Returns an authorized API client.
  16. * @return Google_Client the authorized client object
  17. */
  18. function getClient()
  19. {
  20. $client = new Google_Client();
  21. $client->setApplicationName(APPLICATION_NAME);
  22. $client->setScopes(SCOPES);
  23. $client->setAuthConfig(CLIENT_SECRET_PATH);
  24. $client->setAccessType('offline');
  25. // Load previously authorized credentials from a file.
  26. $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  27. if (file_exists($credentialsPath)) {
  28. $accessToken = json_decode(file_get_contents($credentialsPath), true);
  29. } else {
  30. // Request authorization from the user.
  31. $authUrl = $client->createAuthUrl();
  32. printf("Open the following link in your browser:\n%s\n", $authUrl);
  33. print 'Enter verification code: ';
  34. $authCode = trim(fgets(STDIN));
  35. // Exchange authorization code for an access token.
  36. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
  37. // Store the credentials to disk.
  38. if (!file_exists(dirname($credentialsPath))) {
  39. mkdir(dirname($credentialsPath), 0700, true);
  40. }
  41. file_put_contents($credentialsPath, json_encode($accessToken));
  42. printf("Credentials saved to %s\n", $credentialsPath);
  43. }
  44. $client->setAccessToken($accessToken);
  45. // Refresh the token if it's expired.
  46. if ($client->isAccessTokenExpired()) {
  47. $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
  48. file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  49. }
  50. return $client;
  51. }
  52. /**
  53. * Expands the home directory alias '~' to the full path.
  54. * @param string $path the path to expand.
  55. * @return string the expanded path.
  56. */
  57. function expandHomeDirectory($path)
  58. {
  59. $homeDirectory = getenv('HOME');
  60. if (empty($homeDirectory)) {
  61. $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  62. }
  63. return str_replace('~', realpath($homeDirectory), $path);
  64. }
  65. // Get the API client and construct the service object.
  66. $client = getClient();
  67. $service = new Google_Service_Sheets($client);
  68. // Prints the names and majors of students in a sample spreadsheet:
  69. // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
  70. $spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
  71. $range = 'Class Data!A2:E';
  72. $response = $service->spreadsheets_values->get($spreadsheetId, $range);
  73. $values = $response->getValues();
  74. if (count($values) == 0) {
  75. print "No data found.\n";
  76. } else {
  77. print "Name, Major:\n";
  78. foreach ($values as $row) {
  79. // Print columns A and E, which correspond to indices 0 and 4.
  80. printf("%s, %s\n", $row[0], $row[4]);
  81. }
  82. }