Kode PHP – Search List dan Video YouTube Data API v.3

Kode PHP YouTube Data API 3 yang sederhana untuk menampilkan video hasil pencarian kata kunci dan video id.

Kode API youtube versi 1 tidak dapat digunakan lagi, untuk versi terbarunya yaitu YouTube Data API Version 3. Cara mudah untuk menampilkan daftar video Youtube berdasarkan kata kunci dan id video di situs atau aplikasi Anda, bisa dengan function PHP yang sederhana seperti ini:

Kode untuk menampilkan hasil

Search List
Untuk menampilkan video dari hasil pencarian berdasarkan kata kunci yang Anda tentukan.

jv_youtube('YOUR KEYWORD');

Single Video
Untuk menampilkan single video berdasarkan video id yang ditentukan. Cara mengetahui video id, misalnya pada link video YouTube https://www.youtube.com/watch?v=QqzekYZdBEo,
kode acak dalam link seperti ini QqzekYZdBEo adalah video id-nya.

jv_youtube('VIDEO ID','video');

Kombinasi dengan Form Search Box

$query = $_GET['x'];
echo '<form>
			<select name="type">
				<option value="search">List</option>
				<option value="videos">Video</option>
			</select>
			<input type="text" name="x" class="form-control" placeholder="Type Keywords or Video ID" value="'.$query.'" required>
			<button type="submit">SUBMIT</button>
	  </form>';
if(isset($query)){
	switch($_GET['type']){
		case 'videos';
			jv_youtube($query,'videos');
		break;
		default:
			jv_youtube($query);
		break;
	}
}

Kode function PHP YouTube API V.3

Simpan kode function berikut di bawah salah satu kode di atas atau di file khusus functions theme atau template situs Anda.

/**
 * Simple PHP Youtube Data API V.3
 * Code @jevuska https://www.jevuska.com/
 * Reference https://developers.google.com/youtube/v3/
 ***
 * USAGE
 ***
 * Search list function: jv_youtube('YOUR KEYWORD');
 * Single video function: jv_youtube('VIDEO ID','video');
 ***
 * With form query parameter 'x':
$query = $_GET['x'];
echo '<form>
			<select name="type">
				<option value="search">List</option>
				<option value="videos">Video</option>
			</select>
			<input type="text" name="x" class="form-control" placeholder="Type Keywords or Video ID" value="'.$query.'" required>
			<button type="submit">SUBMIT</button>
	  </form>';
if(isset($query)){
	switch($_GET['type']){
		case 'videos';
			jv_youtube($query,'videos');
		break;
		default:
			jv_youtube($query);
		break;
	}
}
 */

function jv_youtube_setup(){
	//setup Google API Key, create here https://console.developers.google.com/project/
	define('GOOGLE_API_KEY', 'your-google-api-key-here');
	
	//setup PART video api data - allowed values: [snippet,contentDetails,statistics,status]
	define('PART_VIDEO_DATA', 'snippet,contentDetails,statistics,status');
	define('PART_SEARCH_LIST_DATA', 'snippet');

	//setup as 'true' or 'false' to show Video Details and Statistics
	define('VIDEO_DETAILS',true);
	define('VIDEO_STATS', true);
	define('PLAYER', true);

	//setup search list - optional
	define('MAX_RESULT', '5'); //list file per page, min default is 5, max is 50
	define('SEARCH_TYPE', 'video'); //video, channel, playlist
	define('LIST_ORDER', 'date'); //date, rating, relevance, title, videocount, viewcount
	define('SAFE_SEARCH', 'moderate'); //moderate, strict, none

	//setup your text
	define('TOTAL_RESULT', 'Total Results:');
	define('RESULT_PER_PAGE', 'Results Per Page:');
		//write cacheing logic to implement this feature, ie: CACHE LITE PHP
			// define( 'NEXT_PAGE_TOKEN', 'Next Page Token:' ); 
			// define( 'PREVIOUS_PAGE_TOKEN', 'Previous Page Token:' );
	define('VIDEO_TITLE', 'Title:');
	define('VIDEO_DESCRIPTION', 'Description:');
	define('VIDEO_ID', 'Video Id:' );
	define('LINK_VIDEO', 'Link Video:');
	define('CHANNEL_TITLE', 'Channel Title:');
	define('CHANNEL_ID', 'Channel Id:');
	define('LINK_CHANNEL', 'Link Channel:');
	define('VIDEO_THUMBNAIL', 'Thumbnail:');
	define('VIDEO_PLAYER', 'Video Player:');
	define('TIME_PUBLISH', 'Published:');
	define('VIDEO_DURATION', 'Duration:');
	define('VIDEO_DIMENSION', 'Dimension:');
	define('VIDEO_DEFINITION', 'Definition:');
	define('VIDEO_CAPTION', 'Caption:');
	define('VIDEO_LICENSE', 'License:');
	define('COUNT_VIDEO_VIEW', 'View:');
	define('COUNT_VIDEO_LIKE', 'Like:');
	define('COUNT_VIDEO_DISLIKE', 'Dislike:');
	define('COUNT_VIDEO_FAVORITE', 'Favorite:');
	define('COUNT_VIDEO_COMMENT', 'Comment:');
}

function _jv_youtube_data($q,$type=''){
	jv_youtube_setup();
	switch($type){
		case 'videos':
			$data = array(
				'key' => GOOGLE_API_KEY,
				'id' => $q, //video id
				'part' => PART_VIDEO_DATA,
				//MORE OPTION https://developers.google.com/youtube/v3/
			);
		break;
		default:
			$type = 'search';
			$data = array(
				'key' => GOOGLE_API_KEY,
				'q' => urlencode($q), //query search parameter
				'part' => PART_SEARCH_LIST_DATA,

				//START OPTIONAL - comment this rest option if not used (add //)
				'maxResults' => MAX_RESULT,
				'type' => SEARCH_TYPE,
				'order' => LIST_ORDER,
				'safeSearch' => SAFE_SEARCH,
				//END OPTIONAL
				//MORE OPTION https://developers.google.com/youtube/v3/docs/search/list
			);
		break;
	}

	$param = http_build_query($data);
	$json = "https://www.googleapis.com/youtube/v3/$type?$param";
	$str = @file_get_contents($json);
	return $str;
}

function jv_youtube($q, $type = '',$inline = ''){
	$result = '';
	$str = _jv_youtube_data($q, $type);
	if($str === FALSE)	:
		// error handling
		$msg = "Invalid parameter file_get_contents";
		$result .= sprintf('%s', $str);
	else :
		$result .= _jv_search_youtube($str, $type, $inline);
	endif;
	
	if($inline == 'inline')
		return $result;
	else
		print $result;
}

function _jv_search_youtube($str, $type, $inline){
	$doc = json_decode($str, true);
	$respon = array();
	
	$totalresult = (int) $doc['pageInfo']['totalResults'];
	$resultsperpage = (int) $doc['pageInfo']['resultsPerPage'];

	if(empty($inline)){
		if ( defined( 'TOTAL_RESULT' ) )
		$respon[] = sprintf('<b><b>%1$s</b></b> %2$s',TOTAL_RESULT,$totalresult);
		if ( defined( 'RESULT_PER_PAGE' ) )
		$respon[] = sprintf('<b>%1$s</b> %2$s',RESULT_PER_PAGE,$resultsperpage);
	}
	if(empty($type)){
		$nextpage =  $doc['nextPageToken'];
		$prevpage =  $doc['prevPageToken'];
		
		if ( defined( 'NEXT_PAGE_TOKEN' ) )
		$respon[] =  sprintf('<b>%1$s</b> %2$s',NEXT_PAGE_TOKEN,$nextpage);
		if ( defined( 'PREVIOUS_PAGE_TOKEN' ) )
		$respon[] =  sprintf('<b>%1$s</b> %2$s',PREVIOUS_PAGE_TOKEN,$prevpage);
	}
	$i = 0;
	foreach($doc['items'] as $item) {
		$i++;
		if(empty($inline)){
			$title = $item['snippet']['title']; //video title
			$description = $item['snippet']['description']; //video description
			
			$published = $item['snippet'] ['publishedAt']; //published time
			//date format http://php.net/manual/en/datetime.formats.date.php
			$datepublish = date('d-m-Y',strtotime($published));
			
			$videoid = '';
			if(isset($item['id']['videoId']))
				$videoid .= $item['id']['videoId'];
			else
				$videoid .= $item['id'];
			$video_url = "https://www.youtube.com/watch?v=$videoid"; //video url
			$channelid = $item['snippet'] ['channelId']; //channel id
			$thumbnail_url = $item['snippet']['thumbnails']['medium']['url'];//thumbnail option: Allowed values: [default, medium, high]
			$channel_url = "https://www.youtube.com/channel/$channelid"; //channel url
			
			$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_TITLE,$title);
			$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DESCRIPTION,$description);
			if ( defined( 'VIDEO_ID' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_ID,$videoid);
			if ( defined( 'CHANNEL_ID' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',CHANNEL_ID,$channelid);
			if ( defined( 'TIME_PUBLISH' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',TIME_PUBLISH,$datepublish);
			if ( defined( 'VIDEO_THUMBNAIL' ) )
				$respon[] = sprintf('<b>%1$s</b><br><img src="%2$s">',VIDEO_THUMBNAIL,$thumbnail_url);
			if ( PLAYER == true )
				$respon[] = sprintf("<b>%s</b><br><div id='player-$i' class='player' data-id='$videoid'></div>",VIDEO_PLAYER);
			if ( defined( 'LINK_VIDEO' ) )
				$respon[] = sprintf('<b>%1$s</b> <a href="%2$s">%2$s</a>',LINK_VIDEO,$video_url);
			if ( defined( 'LINK_CHANNEL' ) )
				$respon[] = sprintf('<b>%1$s</b> <a href="%2$s">%2$s</a>',LINK_CHANNEL,$channel_url);
		}
		
		if($type == 'videos'){
			$channelititle = $item['snippet'] ['channelTitle']; //channel title
			if ( defined( 'CHANNEL_TITLE' ) )
				$respon[] = sprintf('<b>%1$s</b> %2$s',CHANNEL_TITLE,$channelititle);
			$details = $item['contentDetails'];
			$statistics = $item['statistics'];
			if ( VIDEO_DETAILS == true){
				foreach( array($details) as $item ) {
					$duration = covtime($item['duration']);
					$dimension = $item['dimension'];
					$definition = $item['definition'];
					$caption = $item['caption'] != 'false' ? $item['caption']: '-';
					$license = $item['licensedContent'];
					if ( defined( 'VIDEO_DURATION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DURATION,$duration);
					if ( defined( 'VIDEO_DIMENSION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DIMENSION,$dimension);
					if ( defined( 'VIDEO_DEFINITION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_DEFINITION,$definition);
					if ( defined( 'VIDEO_CAPTION' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_CAPTION,$caption);
					if ( defined( 'VIDEO_LICENSE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',VIDEO_LICENSE,$license);
				}
			}
		
			if ( VIDEO_STATS == true ){
				foreach( array($statistics) as $item ) {
					$view = $item['viewCount'];
					$like = $item['likeCount'];
					$dislike = $item['dislikeCount'];
					$favorite = $item['favoriteCount'];
					$comment = $item['commentCount'];
					if ( defined( 'COUNT_VIDEO_VIEW' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_VIEW,$view);
					if ( defined( 'COUNT_VIDEO_LIKE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_LIKE,$like);
					if ( defined( 'COUNT_VIDEO_DISLIKE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_DISLIKE,$dislike);
					if ( defined( 'COUNT_VIDEO_FAVORITE' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_FAVORITE,$favorite);
					if ( defined( 'COUNT_VIDEO_COMMENT' ) )
						$respon[] = sprintf('<b>%1$s</b> %2$s',COUNT_VIDEO_COMMENT,$comment);
				}
			}
			$respon[] = '<hr>';	
		}
		if(empty($type))
			$respon[] = jv_youtube($videoid,'videos','inline');
	}
	$result = implode('<br>',$respon);
	return $result;
}

function covtime($youtube_time) {
	//function convert youtube time. Source: http://stackoverflow.com/questions/24393230/convert-youtube-api-v3-video-duration-in-php
    preg_match_all('/(\d+)/',$youtube_time,$parts);
    if (count($parts[0]) == 1) {
        array_unshift($parts[0], "0", "0");
    } elseif (count($parts[0]) == 2) {
        array_unshift($parts[0], "0");
    }

    $sec_init = $parts[0][2];
    $seconds = $sec_init%60;
    $seconds_overflow = floor($sec_init/60);

    $min_init = $parts[0][1] + $seconds_overflow;
    $minutes = ($min_init)%60;
    $minutes_overflow = floor(($min_init)/60);

    $hours = $parts[0][0] + $minutes_overflow;

    if($hours != 0)
        return $hours.':'.$minutes.':'.$seconds;
    else
        return $minutes.':'.$seconds;
}

Berikut kode JavaScript jika ingin menampilkan video player secara asyncronous.

<script>
//https://developers.google.com/youtube/iframe_api_reference
//http://stackoverflow.com/a/901144
	var tag = document.createElement('script');

	tag.src = "https://www.youtube.com/iframe_api";
	var firstScriptTag = document.getElementsByTagName('script')[0];
	firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    players = new Array();
	var player = document.getElementsByClassName('player');
	function onYouTubeIframeAPIReady() {
		for (var i = 0; i < player.length; i++) {
			t = new YT.Player(player[i].getAttribute('id'), {
				height: '390',
				width: '640',
				videoId: player[i].getAttribute('data-id'),
				events: {
					//'onReady': onPlayerReady,
					'onStateChange': onPlayerStateChange
				}
			});
			players.push(t);
		}
	}

	function onPlayerReady(event) {
		event.target.playVideo();
	}

	function onPlayerStateChange(event) {
		var temp = event.target.getVideoUrl();
		if (event.data == YT.PlayerState.PLAYING) {
			for (var i = 0; i < players.length; i++) {
              if (players[i].getVideoUrl() != temp) {
				  setTimeout(players[i].stopVideo, 6000);
				  players[i].stopVideo();
			  }
			}
        }
	}

	function getParameterByName(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
			results = regex.exec(location.search);
		return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	}
</script>

Set-up Google API Key Anda (ganti your-google-api-key-here pada kode function di atas), petunjuk tambahan lainnya ada dalam kode tersebut.

Youtube API 3 Search List Demo
Tampilan Script PHP Youtube API 3 Search

Kode PHP Video YouTube Data API v.3 ini tidak menggunakan Google Client API PHP library, jadi cukup sederhana untuk Anda terapkan di situs seperti WordPress atau aplikasi Anda. Kode untuk tampilan dan referensi lainnya bisa temukan di Google Developer YouTube Data API. Semoga bermanfaat.

Author: Jevuska

Rachmanuddin Chair Yahya a.k.a Jevuska is the founder of Jevuska.Com, a qualified web about offering medical articles, blogging, tips, and tutorial of WordPress. Having written for Jevuska since 2007.

14 thoughts on “Kode PHP – Search List dan Video YouTube Data API v.3”

  1. duh baru lagi, yang bing xml aku belum selesai dah di buat puyeng lagi ma yang ini.
    ask lagi om:
    1. kalo buat wp implementasinya gimana kode2 diatas di letakan dimana saja? kode 2 sy letakan di function.php, lalu kode terakhir saya letakan di search.php apa sudah benar? soalnya ada error.

    2. apa bisa diterapkan di hosting gratis seperti 000webhost, nyubi om buat blajar

  2. sukses bang :)
    r************dot****/masakan/resep-laksa-oncom.html
    linknya disensor ya bang :)
    makasih banyak abang ganteng :)

  3. kalo mau dimasukin disearch result wordpress gimana bang?maksudnya keyword youtubenya sesuai dengan pencarian di wordpress?jadi kalo misal digabung ama stt2 langsung nongol video yg sesuai keyword yang digenerate otomatis ama stt2 tersebut,
    lama gak online nih bang :D lagi sibuk ya?postingan ane nunggu dimoderasi semua :v

    1. Kata 'YOUR KEYWORD' atau 'VIDEO ID' dalam function jv_youtube('YOUR KEYWORD'); diganti:

      jv_youtube(get_search_query());
      jv_youtube(get_search_query(),'video');
      

      Jika menggunakan formnya:
      $query = $_GET['x']; diganti:

      $query = get_search_query();
      

      name="x" diganti jadi name="s"

  4. kalau buat extraxt link download video dan audio youtube berdasarkan ID youtube gimana om, kan udah sukses bikin search list lalu pengen bikin halaman download, jadi butuh extract link download youtube video+audionya :D

  5. keren, oh ya mas saya pakai AGC dengan api youtube tapi bingung gimana cara injek keyword manualnya, mohon pencerahannya,

  6. Om jev.. kalo dibuat di single post gimana ya om?
    Jadi judul post “blablabla”
    Otomotis di halaman post ada tampilan video sesuai keyword

    Trim’s

Leave a Reply

Your email address will not be published. Required fields are marked *

Use tag [php] to add code, e.g. [php]<?php echo $var; ?>[/php]