【问题标题】:How can I show the content of a text file with Google Drive Api v3 and php?如何使用 Google Drive Api v3 和 php 显示文本文件的内容?
【发布时间】:2020-05-12 09:03:57
【问题描述】:

我想显示存储在 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();

你能帮帮我吗?

【问题讨论】:

  • this 回答可能有帮助
  • 不知道怎么用,可以举个例子吗?
  • 点击@jibsteroos 评论中的链接,最终将引导您here,进入文件导出方法。
  • @furman87 但是......导出方法确实下载了另一个 mimetype 的文件,我希望将内容的文本作为字符串,以便我可以在 PHP 中处理它

标签: php google-drive-api


【解决方案1】:
  • 您想使用 Drive API 从 Google Drive 中检索文件内容。
    • 该文件是不是 Google 文档(Google 文档、电子表格、幻灯片等)的文本文件。
  • 您希望通过 php 使用 google-api-php-client 来实现此目的。
  • 您已经能够使用 Drive API 从 Google Drive 获取值。

如果我的理解是正确的,那么这个答案呢?请使用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"))

参考资料:

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

补充:

模式一:

当您想使用通过 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.
  • 当您运行此脚本时,会下载文件并将其保存为文件。

【讨论】:

  • 是的,我认为您理解正确,但为了更具体的清楚,我需要的是文本文件中的文本作为字符串。我尝试了你的建议,但它给我带来了这个错误:致命错误:未捕获的 Google_Service_Exception:{“错误”:{“错误”:[{“域”:“全局”,“原因”:“appNotAuthorizedToFile”,“消息”:“用户尚未授予应用程序***对文件***的读取权限。”,“locationType”:“header”,“location”:“Authorization”}],“code”:403,“message”:“用户尚未授予应用程序 *** 对文件的读取权限 ***" }...我使用我的连接设置编辑我的帖子。
  • @Vincenzo Auriemma 感谢您的回复。我带来的不便表示歉意。根据您的回复和添加的脚本,我更新了我的答案。你能确认一下吗?不幸的是,从您的附加脚本中,我无法理解您要使用哪个访问令牌或 API 密钥。我为此道歉。所以我添加了2个模式。对于这两种模式,都会下载文件并将其保存为文件。如果我误解了您的目标,我深表歉意。
  • 现在我已按照模式 1 进行设置,但问题仍然存在(我都尝试了它们,但没有任何变化)。我想坚持我不想将文件下载为文件,但我希望文本文件中包含的文本作为字符串能够使用 PHP 处理它。
  • @Vincenzo Auriemma 感谢您的回复。我带来的不便表示歉意。关于I want the text contained in the text file as a string,我的第一个示例脚本可以实现这一点。这个怎么样?如果我的第一个示例脚本不是您想要的结果,我不得不为我糟糕的英语水平道歉。到时候,我能问一下你的目标的详细信息吗?我想确认一下。对了,the problem remains是这个吗?
  • 其实我要感谢你的支持。甚至我的英语也不是最好的,因此对可能的误解深表歉意。我只是使用你的第一个代码和 pattern1 的设置,直到昨天晚上它给出了上面指出的错误......现在,没有触及任何东西,它完美地工作。所以是的,你已经实现了我的目标。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2021-11-09
  • 2020-05-23
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
相关资源
最近更新 更多