如何使用Google Drive Api v3和php显示文本文件的内容?

文森佐·奥里埃玛(Vincenzo Auriemma)

我想显示存储在Google云端硬盘文件夹中的文本文件的内容。我正在使用Google Drive Api v3。目前,我只能显示文件名和MimeType,但我需要的是内容。我希望文本文件文本为字符串,我找不到合适的函数。

到目前为止,这是我的代码的一部分

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setAuthConfig('credentials.json');
    $client->setDeveloperKey('$myApiKey'); // API key

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = $myAuthCode;

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
    $service = new Google_Service_Drive($client);

[...]

        $file = $service->files->get($fileId); 
    print "Title: " . $file->getName();
    print "Description: " . $file->getDescription();
    print "MIME type: " . $file->getMimeType();

你能帮助我吗?

Tanaike
  • 您要使用云端硬盘API从Google云端硬盘检索文件内容。
    • 该文件是非Google文档(Google文档,电子表格,幻灯片等)的文本文件。
  • 您想使用带有php的google-api-php-client实现此目的。
  • 您已经可以使用Drive API从Google云端硬盘获取值。

如果我的理解是正确的,那么这个答案呢?alt=media用于下载文件。

修改后的脚本:

$file = $service->files->get($fileId); 
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();

$content = $service->files->get($fileId, array("alt" => "media"));  // Added
print $content->getBody();  // Added
  • $service->files->get($fileId)下载文件元数据。因此,为了下载文件内容,请使用$service->files->get($fileId, array("alt" => "media"))

参考文献:

如果我误解了您的问题,而这不是您想要的方向,我深表歉意。

添加:

模式1:

当您要使用OAuth2检索的访问令牌时,请使用以下脚本。在这种情况下,将https://www.googleapis.com/auth/drive.readonly使用的范围运行脚本时,控制台中将显示用于检索授权代码的URL。因此,请将其放入您的浏览器并授权范围。并将浏览器的代码输入到控制台。这样,就可以获取访问令牌和刷新令牌,并且脚本可以工作。

示例脚本:
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token2.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

$client = getClient();
$service = new Google_Service_Drive($client);

$fileId = "###";  // Please set the file ID of the text file on Google Drive.

// Retrieve file metadata.
$file = $service->files->get($fileId);
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();

// Download file.
$content = $service->files->get($fileId, array("alt" => "media"));
file_put_contents("sample.txt", $content->getBody()); // Please set the filename you want.
  • 运行此脚本时,将下载文件并将其另存为文件。

模式2:

当您要使用API​​密钥时,请使用以下脚本。在这种情况下,需要公开共享文件。请注意这一点。

示例脚本:
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setDeveloperKey('###');  // Please set your API key.
    return $client;
}

$client = getClient();
$service = new Google_Service_Drive($client);

$fileId = "###";  // Please set the file ID of the text file on Google Drive.

// Retrieve file metadata.
$file = $service->files->get($fileId);
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();

// Download file.
$content = $service->files->get($fileId, array("alt" => "media"));
file_put_contents("sample.txt", $content->getBody()); // Please set the filename you want.
  • 运行此脚本时,将下载文件并将其另存为文件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用 Python 和 Drive API v3 从 Google Drive 下载文件

如何使用Google Drive Java API v3在Google Drive上复制文件?

如何从 Google Drive 上传和下载文件(使用 Rest Api v3)

如何使用NodeJS和Google Drive API v3将文件移至垃圾箱

如何使用Python和Drive API v3下载Google云端硬盘文件

如何使用Google Drive API上传文件?

Google Drive PHP v3 API文件元数据

如何从 google drive api v3 获取文件列表?

使用Google Drive API v3获取Google文档的文件内容

使用Google Drive API v3移动文件

如何使用Java中的Google Drive API v3获取上载文件到Google Drive的可共享链接

如何使用带有Google Drive API v3 Java的服务帐户访问Team Drive

如何使用带有Google Drive .NET API v3的服务帐户访问Team Drive

使用 Java 和 Google Drive API V3 将文件上传到共享的 Google Drive 位置?

如何使用 Google Drive API V3 将文件上传到 Group Drive(共享驱动器)?

在 Google Drive API V3 中使用 update() 和 addParents 移动文件不会永久生效

使用 google drive API PHP V3 权限错误删除文件

如何使用PHP Google Drive API在Google Drive上上传文件

搜索文件 Google Drive API v3

Google Drive Api v3和proguard

Google Drive API:如何从Google Drive下载文件?

Google Drive API V3 Javascript-创建包含内容的文件

如何过滤Google Drive API v3 mimeType?

如何使用Java从Google Drive API获取Gdoc内容?

使用 pydrive 或 google drive api 在 google drive 中复制文件

使用Google Drive API在指定的Google Drive中上传文件

Flutter-如何使用Google Drive API下载公共文件

如何使用Google Drive API通过Java下载文件

如何使用Google Drive API for Ruby重命名文件?