esedic
1/19/2016 - 8:37 PM

Get Youtube thumbnail with Youtube API & PHP

Get Youtube thumbnail with Youtube API & PHP

<?php
	$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=AIzaSyCFyxv5HakPI_8QdsKNuMIE_W0mfNIw1Ts&part=snippet&id=Uph5MuE_CJg");
	$json = json_decode($data);
	$highImg = $json->items[0]->snippet->thumbnails->high->url;
	$maxresImg = $json->items[0]->snippet->thumbnails->maxres->url;
?>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
		<title>Youtube API</title>
		<style>
			div {
				max-width: 1000px;
				margin: 50px auto;
				text-align: center;
				padding: 20px;
			}
			img {
				display: block;
				max-width: 100%;
			}
		</style>
	</head>
	<body>
		<div>
			<?php 
			  // if maximum quality image doesn't exists, use high quality
			  if (is_null($maxresImg)) 
			  {
  				echo '<img src="'.$highImg.'" alt="Image">';
			  }
			  else 
			  // if maximum quality image exists, use it
			  {
  				echo '<img src="'.$maxresImg.'" alt="Image">';
			  }
			?>
		</div>
	</body>
</html>