たけるのプログラミング

作ったものとか、気ままにアップします。

【PHP】YouTubeのDATA APIを使ってみた。

こんにちは、なんとなくYouTubeのデータを使ってプログラムを書きたいと思ったので、

PHPを使って、YouTubeのDATA APIを使ってみたいと思います。

GoogleデベロッパーコンソールからAPIキーの獲得の流れについては以下記事が分かりやすいです。
qiita.com

実際に、公式のデモを動かしてみました。

実行結果

キーワードを入力して、最大表示数を指定して、
f:id:takeru232423:20210530212006p:plain

検索すると
f:id:takeru232423:20210530212120p:plain
該当する動画タイトルやid、チャンネルが表示されました。

ソースコード

Search: list  |  YouTube Data API  |  Google Developers ←公式サイト載っています。

<?php

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';

$htmlBody = <<<END
<form method="GET">
  <div>
    Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
  </div>
  <div>
    Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="50" step="1" value="25">
  </div>
  <input type="submit" value="Search">
</form>
END;

// This code will execute if the user entered a search query in the form
// and submitted the form. Otherwise, the page displays the form above.
if (isset($_GET['q']) && isset($_GET['maxResults'])) {
  /*
   * Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
   * Google API Console <https://console.developers.google.com/>
   * Please ensure that you have enabled the YouTube Data API for your project.
   */
  $DEVELOPER_KEY = 'REPLACE_ME';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  // Define an object that will be used to make all API requests.
  $youtube = new Google_Service_YouTube($client);

  $htmlBody = '';
  try {

    // Call the search.list method to retrieve results matching the specified
    // query term.
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';
    $playlists = '';

    // Add each result to the appropriate list, and then display the lists of
    // matching videos, channels, and playlists.
    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['videoId']);
          break;
        case 'youtube#channel':
          $channels .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['channelId']);
          break;
        case 'youtube#playlist':
          $playlists .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['playlistId']);
          break;
      }
    }

    $htmlBody .= <<<END
    <h3>Videos</h3>
    <ul>$videos</ul>
    <h3>Channels</h3>
    <ul>$channels</ul>
    <h3>Playlists</h3>
    <ul>$playlists</ul>
END;
  } catch (Google_Service_Exception $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }
}
?>

<!doctype html>
<html>
  <head>
    <title>YouTube Search</title>
  </head>
  <body>
    <?=$htmlBody?>
  </body>
</html>

ポイント

 $DEVELOPER_KEY = 'REPLACE_ME';

の 'REPLACE_ME'は自分のAPIキーを記述します。

$searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

の’id,snippet’のpart部分は必須パラメータで、id、snipperは以下スクリーンショットの通りとなっている。
f:id:takeru232423:20210530213041p:plain
f:id:takeru232423:20210530213215p:plain
f:id:takeru232423:20210530213232p:plain


第二パラメータには連想配列としてキーが’q’の値と、’maxResults’の値が指定されている。各値の説明は以下スクリーンショット通り。
f:id:takeru232423:20210530213336p:plain
f:id:takeru232423:20210530213350p:plain


そして$searchResponseに検索結果が代入され、あとは$searchResponseから欲しいデータを抜き取る作業をするだけです。


$searchResponseで取得できるリソースは複数あり、
例えばリソースがvideoかchannelかplaylistかを判断するために、以下スクリーンショットのkindの部分で判断することができます。
videoの場合:
"kind": "youtube#video"
channelの場合:
"kind": "youtube#channel",
Playlistの場合:
"kind": "youtube#playlist"
f:id:takeru232423:20210530213602p:plain



比較的に簡単にAPIを使うことができました。 近いうちにこのAPIを利用したWEBアプリを作りたいです。

間違えなど、ご指摘がありましたらよろしくお願いいたします。