【发布时间】:2016-02-11 05:58:48
【问题描述】:
我的应用程序支持从 Excel 文档导入数据。我想通过复制粘贴链接(而不是保存并从下载文件夹中选择)来添加对从 Google Drive 电子表格导入数据的支持。
此代码适用于公开可用的文件(通过共享链接):
$url = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=...&exportFormat=xlsx';
file_put_contents('path/to/file.xlsx', file_get_contents($url));
然后我将保存文件路径传递给导入器,它就可以工作了。
对于私人文件,此代码没有意义,因为我们收到权限错误,并且检索的是 HTML 而不是 Excel 数据。
我按照Using OAuth 2.0 for Web Server Applications文章中描述的步骤安装了最新版本的google/google-api-php-client。
我的oauth2callback.php 文件内容:
<?php
require_once '../../vendor/autoload.php';
session_start();
$client = new Google_Client;
$client->setAuthConfigFile('/path/to/google_auth_config.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAccessType('offline');
if (!isset($_GET['code'])) {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirectUri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirectUri, FILTER_SANITIZE_URL));
}
主要代码如下:
$client = new Google_Client;
$client->setAuthConfig('/path/to/google_auth_config.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$driveService = new Google_Service_Drive($client);
$fileId = '...';
// For testing purposes
$file = $driveService->files->get($fileId);
$content = $driveService->files->get($fileId, ['alt' => 'media']);
$content = $driveService->files->export(
$fileId,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
['alt' => 'media']
);
} else {
$redirectUri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirectUri, FILTER_SANITIZE_URL));
}
这个:
$file = $driveService->files->get($fileId);
工作正常,我得到有效的Google_Service_Drive_DriveFile 实例。
下载示例取自 Download Files 文档。
这个:
$content = $driveService->files->get($fileId, ['alt' => 'media']);
抛出异常:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "badRequest",
"message": "The specified file does not support the requested alternate representation.",
"locationType": "parameter",
"location": "alt"
}
],
"code": 400,
"message": "The specified file does not support the requested alternate representation."
}
}
这个:
$content = $driveService->files->export(
$fileId,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
['alt' => 'media']
);
给出一个错误:
调用未定义的方法 Google_Service_Drive_Files_Resource::export()
用户拥有此共享文件夹的编辑权限,downloadUrl 和 exportLinks 属性在 $file 中是 null,但我可以获得类似 title 的属性。
有什么想法吗?
我在Google_Http_Request 中看到了一些其他示例,但它已被 Guzzle 取代,因此现在没用了。
【问题讨论】:
标签: php google-drive-api