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

如何使用Google Drive Api v3和php显示文本文件的内容?,php,google-drive-api,Php,Google Drive Api,我想显示存储在Google Drive文件夹中的文本文件的内容。 我正在使用GoogleDriveAPIv3。 目前,我只能显示文件名和MimeType,但我需要的是内容。我想要文本文件文本作为字符串 我找不到合适的函数 到目前为止,这是我代码的一部分 function getClient() { $client = new Google_Client(); $client->setApplicationName('Google Drive API PHP Quicksta

我想显示存储在Google Drive文件夹中的文本文件的内容。 我正在使用GoogleDriveAPIv3。 目前,我只能显示文件名和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();
你能帮我吗?

  • 您希望使用驱动器API从Google Drive检索文件内容。
    • 该文件是文本文件,不是谷歌文档(谷歌文档、电子表格、幻灯片等)
  • 您希望通过使用带有php的google api php客户端来实现这一点
  • 您已经能够使用驱动API从Google Drive获取值
如果我的理解是正确的,那么这个答案呢?请使用
alt=media
下载文件

修改脚本:
  • $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.
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.
  • 运行此脚本时,将下载该文件并将其另存为文件
模式2: 如果要使用API密钥,请使用以下脚本。在这种情况下,文件需要公开共享。请小心这个

示例脚本:
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.
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.
  • 运行此脚本时,将下载该文件并将其另存为文件

答案可能有用我不知道如何使用它,你能给我一个例子吗?按照@Jibstroos评论中的链接最终会引导你找到文件导出方法。@furman87但是。。。export方法确实使用另一个mimetype下载了文件,相反,我希望将内容的文本作为字符串,这样我可以在PHPYes中处理它,我认为您理解正确,但为了更明确,我需要的是文本文件中的文本作为字符串。我尝试了你的建议,但它给我带来了以下错误:致命错误:未捕获的Google_服务异常:{“错误”:{“错误”:[{“域”:“全局”,“原因”:“appNotAuthorizedToFile”,“消息”:“用户未授予应用***对文件***.”、“位置类型”:“头”,“位置”:“授权”}],“代码”:403,“消息”:“用户尚未授予应用程序对文件***”的***读取权限”…我用我的连接设置编辑了我的帖子。@Vincenzo Auriemma感谢您的回复。对于给我带来的不便,我深表歉意。从您的回复和添加的脚本中,我更新了我的答案。您能确认一下吗?很遗憾,从您的附加脚本中,我无法理解您要使用的是访问令牌还是API密钥。我道歉因此,我添加了2种模式。对于这两种模式,文件都会被下载并保存为文件。如果我误解了您的目标,我很抱歉。现在我在模式1中设置为,但问题仍然存在(我尝试了这两种模式,但没有做任何更改)。我想坚持我不想将文件作为文件下载,但我希望文本文件中包含的文本作为字符串,以便能够使用PHP进行处理。@Vincenzo Auriemma感谢您的回复。对于由此带来的不便,我深表歉意。关于
我希望文本文件中包含的文本作为字符串
,我的第一个示例脚本无法实现他的。怎么样?如果我的第一个示例脚本不是你想要的结果,我必须为我糟糕的英语技能道歉。那时,我可以问你关于你目标的详细信息吗?我想确认一下。顺便问一下,
问题仍然存在
是吗?事实上我必须感谢你的支持。即使我的英语不是最好的o很抱歉可能存在误解。我只是在使用您的第一个代码和pattern1的设置,直到昨天晚上,它才给出上述错误…现在,在没有触及任何内容的情况下,它工作正常。因此,是的,您已经实现了我的目标。谢谢