0
1

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 3 years have passed since last update.

Docker-composeを使って爆速でPHP+YoutubeDataAPIv3を利用

Last updated at Posted at 2020-12-31

##はじめに
YoutubeのAPIを爆速で使いたいという方向けの記事です。
とりあえずPHPでYoutubeDataAPIv3を直ぐに使えるようにできます。

事前準備として下の記事を参考にAPIキーを取得しておいてください。
http://piyohiko.webcrow.jp/kids_tube/help/index.html

参考記事
Dockerのディレクトリ構成については下記のものを参考にしました。
https://tech-blog.rakus.co.jp/entry/20200908/docker

##ファイル構成

├── docker-compose.yml
├── nginx
│   └── default.conf
├── php
│   ├── Dockerfile
│   └── php.ini
└── src
    ├── Youtube.php
    ├── index.php

treeコマンドについては下記の記事を参考に
https://qiita.com/tatema/items/8a1de3d3b87884cb0d21

###docker-compose.yml
Dockerfileやdocker-compose.ymlについての各コマンドについての説明は
DockerでLaravel+MySQL+phpMyadminの環境構築
または
https://tech-blog.rakus.co.jp/entry/20200908/docker
を参考に

docker-compose.yml
version: '3'

services:
  nginx:
    image: nginx:stable-alpine
    ports:
      - "8080:80"
    volumes:
      - ./src:/var/www/html
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf

  php:
    build: ./php
    volumes:
      - ./src:/var/www/html%

###default.conf

default.conf
server {
    listen 80;
    root  /var/www/html;
    index index.php index.html;

    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include       fastcgi_params;
    }
}

###Dockerfile

docker-php-ext-install pdo_mysql
これは不要かと思いますが、いつも僕はDockerfileに入れているので任意でお願いします。

Dockerfile
FROM php:fpm
COPY php.ini /usr/local/etc/php/

RUN apt-get update \
&& apt-get install -y \
git \
zip \
unzip \
vim \
libpng-dev \
libpq-dev \
&& docker-php-ext-install pdo_mysql

RUN cd /usr/bin && curl -s http://getcomposer.org/installer | php && ln -s /usr/bin/composer.phar /usr/bin/composer
RUN cd &&  composer require google/apiclient:~2.0

###php.ini

php.ini
[Date]
date.timezone = "Asia/Tokyo"
[mbstring]
mbstring.internal_encoding = "UTF-8"
mbstring.language = "Japanese"

###index.php
これはつくらなくてもつくってもOK

index.php
<?php
echo "Hello World!";
phpinfo();

###Youtube.php

https://developers.google.com/youtube/v3/code_samples/php?hl=ja
YoutubeDataAPIの公式リファレンスからサンプルコードを引用した

Youtube.php
<?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 = 'ここにGoogleAPIキーを入れてください';

  $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>

ここまでファイルを作成し、ディレクトリへの配置も終わったら、docker-compose.ymlがあるディレクトリで

[Mac]docker-compose build
[Mac]docker-compose up

を実行し、終了後
http://localhost:8080/Youtube.php
にアクセスし、
スクリーンショット 2020-12-31 16.20.40.png

のようなフォームが出ていたらOK

これでYoutubeDataAPIv3が使えるようになった。
https://developers.google.com/youtube/v3/code_samples/php?hl=ja
にたくさんのサンプルコードがあるのでそれを参考にすると色々遊べそう!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?