1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】Youtube Data APIによる動画情報取得

Posted at

Youtube Data APIを試してみました。
PHPの環境があれば、数分で実行まで行けるんじゃないかと思います。
環境:Windows
言語:PHP

コマンドプロンプトで実行できるものです。
これを、ファンクション化したりと、使いまわしできたらいいんじゃないかなと。

参考サイト

公式

事前準備

まず、必要なライブラリをインストール 対象のphpファイルを置くディレクトリとかで。

^2.0

APIキーの取得

GoogleのAPIとサービス

こちらのAPIキーの取得の手順が参考になります。
APIキーを生成したら、メモっておいてください。

証明書の配置

以下のURLの「証明書の配置」が参考になります。
http://azwoo.hatenablog.com/entry/2017/12/15/004353
cacert.pemをダウンロードし、
「C:\php\extras\ssl\cacert.pem」のように、PHPインストールフォルダ内に配置してください。

コード

youtubeApitest.php
<?php

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

const MAX_SNIPPETS_COUNT = 5;
const DEFAULT_ORDER_TYPE = 'date';
const DEFAULT_TYPE = 'video';
const CHHANNEL_ID = 'UCL6JY2DXJNDOIqCP1CRADng';//某ちゃんねる
const API_KEY = "AIzaSyA-YBJhfKrI-aaaaaaaaaaaaaaaaaaaa";

  // Googleクライアントのインスタンス
  $http = new GuzzleHttp\Client([
    'verify' => 'C:\php\extras\ssl\cacert.pem'
    ]);
  $client = new Google_Client;
  $client->setHttpClient($http);
  $client->setApplicationName("youtube-api-data-test");
  $client->setDeveloperKey(API_KEY);

  // Youtubeのインスタンス
  $youtube = new Google_Service_YouTube($client);

  //ここに好きなYouTubeのチャンネルIDを入れる
  $params['channelId'] = CHHANNEL_ID;
  $params['type'] = DEFAULT_TYPE;
  $params['maxResults'] = MAX_SNIPPETS_COUNT;
  $params['order'] = DEFAULT_ORDER_TYPE;
  try {

      $searchResponse = $youtube->search->listSearch('snippet', $params);

  } catch (Google_Service_Exception $e) {
      echo htmlspecialchars($e->getMessage());
      exit;
  } catch (Google_Exception $e) {
      echo htmlspecialchars($e->getMessage());
      exit;
  }

  foreach ($searchResponse['items'] as $searchResult) {
    switch ($searchResult['id']['kind']) {
      case 'youtube#video':
        $videos = sprintf('<li>%s (%s)</li>',
            $searchResult['snippet']['title'], $searchResult['id']['videoId']);
            echo "タイトル:".$searchResult['snippet']['title']." URL:https://www.youtube.com/watch?v=".$searchResult['id']['videoId'];
        break;

    }
  }

実行コマンド

php  youtubeApitest.php

補足

この定数に、上記の事前準備で取得したAPIキーをセットします。

Googleクライアントの初期化をします。上記の「証明書の配置」で配置したパスを「verify」で指定します。
  $http = new GuzzleHttp\Client([
    'verify' => 'C:\php\extras\ssl\cacert.pem'
    ]);
  $client = new Google_Client;
  $client->setHttpClient($http);
  $client->setApplicationName("youtube-api-data-test");
  $client->setDeveloperKey(API_KEY);
これをやらないと、以下の感じがでます。コンポーザーでインストールした「google/apiclient」のバージョンも影響あるらしく、エラー解消しない場合は、再インストールを・・。(自分はそれで解消)
PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in C:\develop\ga-php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:187
条件指定をします。パラメータについては、リファレンス Videosの「プロパティ」を見てみてください。
  $params['channelId'] = CHHANNEL_ID;
  $params['type'] = DEFAULT_TYPE;
  $params['maxResults'] = MAX_SNIPPETS_COUNT;
  $params['order'] = DEFAULT_ORDER_TYPE;
取得結果です。echoの所で、動画タイトルとURLを出力しています。取得内容については、先ほどのリファレンス Videosの「プロパティ」を見てみてください。
 foreach ($searchResponse['items'] as $searchResult) {
    switch ($searchResult['id']['kind']) {
      case 'youtube#video':
        $videos = sprintf('<li>%s (%s)</li>',
            $searchResult['snippet']['title'], $searchResult['id']['videoId']);
            echo "タイトル:".$searchResult['snippet']['title']." URL:https://www.youtube.com/watch?v=".$searchResult['id']['videoId'];
        break;

    }
  }
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?