forked from magnetikonline/php-google-spreadsheet-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.php
executable file
·110 lines (83 loc) · 2.46 KB
/
example.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env php
<?php
require('base.php');
require('googlespreadsheet/api.php');
require('googlespreadsheet/api/parser.php');
require('googlespreadsheet/api/parser/simpleentry.php');
require('googlespreadsheet/cellitem.php');
require('oauth2/token.php');
require('oauth2/googleapi.php');
class Example extends Base {
public function execute() {
// load OAuth2 token data - exit if false
if (($tokenData = $this->loadOAuth2TokenData()) === false) {
return;
}
// setup Google OAuth2 handler
$OAuth2GoogleAPI = $this->getOAuth2GoogleAPIInstance();
$OAuth2GoogleAPI->setTokenData(
$tokenData['accessToken'],
$tokenData['tokenType'],
$tokenData['expiresAt'],
$tokenData['refreshToken']
);
$OAuth2GoogleAPI->setTokenRefreshHandler(function(array $tokenData) {
// save updated OAuth2 token data back to file
$this->saveOAuth2TokenData($tokenData);
});
$spreadsheetAPI = new GoogleSpreadsheet\API($OAuth2GoogleAPI);
// fetch all spreadsheets and display
$spreadsheetList = $spreadsheetAPI->getSpreadsheetList();
print_r($spreadsheetList);
if (!$spreadsheetList) {
echo("Error: No spreadsheets found\n");
exit();
}
// fetch key of first spreadsheet
$spreadsheetKey = array_keys($spreadsheetList)[0];
// fetch all worksheets and display
$worksheetList = $spreadsheetAPI->getWorksheetList($spreadsheetKey);
print_r($worksheetList);
// fetch ID of first worksheet
$worksheetID = array_keys($worksheetList)[0];
// fetch worksheet data list and display
print_r($spreadsheetAPI->getWorksheetDataList(
$spreadsheetKey,
$worksheetID
));
// fetch worksheet cell list and display
$cellList = $spreadsheetAPI->getWorksheetCellList(
$spreadsheetKey,
$worksheetID,[
'columnStart' => 2,
'columnEnd' => 10
]
);
print_r($cellList);
// update content of first cell
/*
$cellIndex = array_keys($cellList)[0];
$cellList[$cellIndex]->setValue(
$cellList[$cellIndex]->getValue() . ' updated'
);
$spreadsheetAPI->updateWorksheetCellList(
$spreadsheetKey,
$worksheetID,
$cellList
);
*/
}
private function loadOAuth2TokenData() {
$tokenDataFile = $this->config['tokenDataFile'];
if (!is_file($tokenDataFile)) {
echo(sprintf(
"Error: unable to locate token file [%s]\n",
$tokenDataFile
));
return false;
}
// load file, return data as PHP array
return unserialize(file_get_contents($tokenDataFile));
}
}
(new Example(require('config.php')))->execute();