YouTube Data APIで動画の詳細を取得する
前回はYouTube Data APIで動画の検索を行いました。しかし、これで取得できるのは動画の限られた情報であり、動画の時間や再生回数などは取得できません。そこで、今回は検索結果の動画の詳細情報を取得することにします。
前回はYouTube Data APIの「search」で動画を検索しました。今回は検索結果の動画IDをもとに、YouTube Data APIの「videos」を実行して動画の詳細を取得します。今回は動画の再生時間、再生回数を取得することを目標にします。
https://www.googleapis.com/youtube/v3/videos?id=動画ID&part=snippet&key=API_KEY
前回は「search」でしたが、今回は「videos」です。このままAPIを実行してもいいですが、「&part=snippet」のみでは今回の目標である、再生時間と再生回数の取得ができません。そこで、今回は「&part=snippet,statistics,contentDetails」という風に変更して実行します。(ちなみに「search」では「&part=snippet」か「&part=id」しか対応していません。)
「&part」にstatisticsとcontentDetailsを追加した場合、下のような実行結果になります。
{
"kind": "youtube#videoListResponse",
"etag": "TE2rOOUZEZ2eZr0Fiv3Z2sF9MZU",
"items": [
{
"kind": "youtube#video",
"etag": "LTAYPTmtf0Si1FDdUNTEzeUrIk0",
"id": "51CH3dPaWXc",
"snippet": {
"publishedAt": "2010-04-16T07:09:03Z",
"channelId": "UCEAOVoVVtVBhcn7vLIQIkDA",
"title": "スピッツ / ロビンソン",
"description": "11th single 「ロビンソン」\r\nオリジナル発売日:1995年4月5日",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/51CH3dPaWXc/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/51CH3dPaWXc/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/51CH3dPaWXc/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "spitzclips",
"tags": [
"ロビンソン",
"SPITZ",
"スピッツ",
"草野マサムネ",
"草野正宗",
"三輪テツヤ",
"三輪徹也",
"田村明浩",
"崎山龍男"
],
"categoryId": "10",
"liveBroadcastContent": "none",
"localized": {
"title": "スピッツ / ロビンソン",
"description": "11th single 「ロビンソン」\r\nオリジナル発売日:1995年4月5日"
}
},
"contentDetails": {
"duration": "PT4M29S",
"dimension": "2d",
"definition": "sd",
"caption": "false",
"licensedContent": true,
"contentRating": {},
"projection": "rectangular"
},
"statistics": {
"viewCount": "115862516",
"likeCount": "227237",
"dislikeCount": "13628",
"favoriteCount": "0",
"commentCount": "20178"
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
「contentDetails」の「duration」に再生時間、「statistics」の「viewCount」に再生回数が入っていることが確認できます。
「search」で動画検索の検索結果から動画IDを取得し、さらに、動画IDから「videos」で再生時間と再生回数を表示させます。
PHPで実装
今回もPHPで実装します。HTMLとjavascriptは前回と同様です。「videos」はIDをカンマ区切りで実行することで複数の動画情報を一斉に取得できます。
<?php
header('Content-type: text/plain; charset= UTF-8');
if(isset($_POST['search_str'])){
$search_str = $_POST['search_str'];//検索ワードの取得
$disp_str = htmlEntities($_POST['search_str']);//検索ワード(表示用)
}else{
$search_str = "";
}
if($search_str != "" ){
$apiKey = APIキー;
$apiAddress_y = "https://www.googleapis.com/youtube/v3/search?type=video&q=";
$fragment_y = "&part=snippet";
$order = ""; //再生回数順:&order=viewCount 日付順:&order=date
$maxResults = 10; //検索結果数
$address = $apiAddress_y . str_replace (" " , "%20" ,$search_str) . $fragment_y . "&key=" . $apiKey . "&maxResults=" . $maxResults . $order ;
$json = cuGet_contents( $address ); //詳細データ取得(下のfunction)
$getData = json_decode( $json , true);
$ytMovieID = "";//ここに動画IDをカンマ区切りで追加
foreach ($getData["items"] as $searchResult) {
if( $ytMovieID <> "") {
$ytMovieID =$ytMovieID . "," . $searchResult["id"]["videoId"];
} else {
$ytMovieID = $searchResult["id"]["videoId"];
}
}
$apiAddress_y = "https://www.googleapis.com/youtube/v3/videos?id=";
$fragment_y = "&part=snippet,statistics,contentDetails";
$address = $apiAddress_y . $ytMovieID . $fragment_y . "&key=" . $apiKey;
$json = cuGet_contents( $address ); //詳細データ取得(下のfunction)
$getData = json_decode( $json , true);
$videos = "<h5>" . $disp_str . " : 検索結果</h5>";
$video = "";
foreach ($getData["items"] as $searchResult) {
//動画タイトル(クリックでYouTubeの動画ページへ移動)
$title = sprintf('<a href="https://www.youtube.com/watch?v=%s" target="_blank">%s</a>',
$searchResult["id"],$searchResult["snippet"]["title"]
);
//サムネイル(クリックでYouTubeの動画ページへ移動)
$thumbnails = sprintf('<a href="https://www.youtube.com/watch?v=%s" target="_blank"><img src="%s"></a>',
$searchResult["id"],$searchResult["snippet"]["thumbnails"]["medium"]["url"]
);
//動画のチャンネル(クリックでYouTubeのチャンネルページへ移動)
$channel = sprintf('<a href="https://www.youtube.com/channel/%s" target="_blank">%s</a>',
$searchResult["snippet"]["channelId"],$searchResult["snippet"]["channelTitle"]
);
$video = sprintf('%s<BR>%s<BR>%s<BR>%s<BR>%s<BR>%s<BR>%s<hr>',
$title,
$thumbnails,
"アップロード日付:" . date("Y/m/d",strtotime($searchResult["snippet"]["publishedAt"])),
"チャンネル:" . $channel,
"再生時間:" . str_replace ('PT','',str_replace ('H','時間',str_replace ('M','分',str_replace ('S','秒',$searchResult["contentDetails"]["duration"])))),
"再生回数:" . number_format($searchResult["statistics"]["viewCount"]),
$searchResult["snippet"]["description"] //動画の説明
);
$videos .= $video;
}
$result = nl2br($videos);
echo $result;
}else{
echo "検索ワードを入力してください。";
}
function cuGet_contents( $url_address, $timeout = 15 ){
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url_address );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
$result = curl_exec( $ch );
curl_close( $ch );
return $result;
}
?>
ソースコードはこんなかんじ。
結果
実際に実装してみた。下のテキストボックスに検索ワードを入力して検索ボタンを押すとYouTube動画の再生時間、再生回数付きの検索結果が表示されます。
YouTube:


コメント