PHPを用いてGoogle Drive APIにアクセスするサンプル

ライブラリのインストール

Google Drive APIのクライアントライブラリをComposerを用いてインストールします。

composer require google/apiclient

サンプルコード

以下のサンプルコードを使用してGoogle Driveにアクセスします。

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() !== 'cli') {
    throw new Exception('このアプリケーションはコマンドライン上で実行する必要があります。');
}

/**
 * アウスライズ済みのAPIクライアントを返します。
 * @return Google_Client アウスライズ済みのクライアントオブジェクト
 */
function createClient()
{
    $client = new Google_Client();
    $client->setScope(Google_Service_Drive::DRIVE);
    // サービスアカウントのキー設定
    $client->setAuthConfig('example-service-account.json');
    // 偽装するユーザーのメールアドレス設定
    $client->setSubject('sample@example.com');
    return $client;
}

// 指定された親フォルダー内のドライブファイルを取得します。
function fetchDriveFiles($service, $parentFolderId, $searchKeyword = "")
{
    $query = "'$parentFolderId' in parents";
    if ($searchKeyword !== "") {
        $query .= " and name contains '$searchKeyword'";
    }
    
    $options = array(
        'fields' => 'nextPageToken, files(id, name, parents)',
        'includeItemsFromAllDrives' => true,
        'corpora' => 'drive',
        'supportsAllDrives' => true,
        'q' => $query
    );
    
    $results = $service->files->listFiles($options);
    return $results->getFiles();
}

// 取得したファイル情報を表示します。
function displayFiles($files)
{
    if (empty($files)) {
        echo "ファイルが見つかりませんでした。\n";
    } else {
        echo "ファイル一覧:\n";
        foreach ($files as $file) {
            echo $file->getName() . "  ID: " . $file->getId() . "\n";
        }
    }
}

// クライアントとAPIサービスの初期化
$client = createClient();
$service = new Google_Service_Drive($client);
$files = fetchDriveFiles($service, "0AOYSqx2jksBQUk9PVA");
displayFiles($files);
?>

テストの実行

コマンドラインから以下のコマンドを実行します。

php sample.php

参考資料

タグ: PHP Google Drive API サービスアカウント ファイル一覧取得

6月4日 23:35 投稿