使用php-google-spreadsheet-client读取google sprreadsheet里的内容

使用google spreadsheet协同工作相当方便,几个人一起编辑一个表,如果需要用php读取表里的内容的话,使用php-google-spreadsheet-client这个库相当方便

2015-07-16 11:28:48

官方网址:https://github.com/asimlqt/php-google-spreadsheet-client

安装方法:
使用 composer 安装是最方便的方法,这个库,需要google/apiclient这个库,所以 composer.json,可以写成这样:
{
 "require": {
  "asimlqt/php-google-spreadsheet-client": "2.3.5",
  "google/apiclient": "1.1.4"
 }
}

安装完成后,需要做以下几步:
1 https://console.developers.google.com/project 在这里申请一个新的project,在APIs加入 Drive API

2 在credential 里得到 Client ID 与 Email address

3 把第二步里的Email address,加入到你要读取的spreadsheet的共享人里

代码:
1 认证

$G_CLIENT_ID = 'XXXXXXXXXXX Client ID XXXXXXXXXXX';
$G_CLIENT_EMAIL = 'XXXXXXXXXXX Email address XXXXXXXXXXX';
$G_CLIENT_KEY_PATH = 'XXXXXXXXXXX P12 key XXXXXXXXXXX';
$G_CLIENT_KEY_PW = 'notasecret';

$obj_client_auth = new Google_Client ();
$obj_client_auth->setApplicationName ('sApplication');
$obj_client_auth->setClientId ($G_CLIENT_ID);
$obj_client_auth->setAssertionCredentials (new Google_Auth_AssertionCredentials(
  $G_CLIENT_EMAIL,
  array('https://spreadsheets.google.com/feeds','https://docs.google.com/feeds'),
    file_get_contents ($G_CLIENT_KEY_PATH),
    $G_CLIENT_KEY_PW
));

2 读取内容

$obj_client_auth->getAuth()->refreshTokenWithAssertion();
$obj_token = json_decode($obj_client_auth->getAccessToken());
$accessToken = $obj_token->access_token;

$serviceRequest = new Google\Spreadsheet\DefaultServiceRequest($accessToken);
Google\Spreadsheet\ServiceRequestFactory::setInstance($serviceRequest);

$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
$spreadsheet = $spreadsheetFeed->getByTitle("spreadsheet名");//找到文件
$worksheetFeed = $spreadsheet->getWorksheets();//打开文档

$worksheet = $worksheetFeed->getByTitle("sheet名");//打开sheet
$listFeed = $worksheet->getListFeed();

徜徉于这片废土的我们.....应当去哪里追寻更好的自己?