Integrate YouTube API with PHP for data and Video Analytics

YouTube is currently world’s most popular video sharing website. Over three billion hours of videos are watched every month and over 72 hours of video content is uploaded every minute. It also provides offline facility in which you can watch video offline once you save it. Today we would know about YouTube API with PHP. By using YouTube API, You can find all channels and videos statistics or analytics as well as manage your channels and video.

You can create awesome application using YouTube API and also upload and create video from your application. There are few website which provides these type data. If you are thinking to make application using YouTube API then you are at right place will describe all things about it.

There are two main YouTube API which is used to get all channel and video data as follows:

1.    YouTube Data API (V3)

2.    YouTube Analytics API

YouTube Data API (V3)

YouTube data API Provides basic details or activity of channels and videos using an authorized API Key like you can get all views, shares, like, dislike, comment and lot of things of any video and channel on your own website. It provides data without asking user authorization, only should have valid API Key of any. To find details of channel follow these steps:

    1.   Make a App by going to http://console.developers.google.com/ .Login from your Gmail Account after that click on create project option will have following page as shown below:

2.    After clicking on create project button, you will see following page as shown below. Enter your Project name whatever you want and click on create button.

3.    Now you will see three option in left hand side i.e. dashboard, library and credentials. Click on credentials option will have following page as shown below. Click on create project button will generate pop to ask Project Name again then click on create button.

4.    Click on create button will redirect to following page then it will ask for create credentials. Select an API Key option to generate API Key. You can also generate client and secret key by clicking on Oath Client ID option.

5.    After Generating API Key, you will have following page as shown below will use further in PHP code to get YouTube channel Details.

6.    Download library from Google folder of attached demo and create file youtube.php file and put following code will get all channel details. Here you have to put your API Key of App.

<?php
if (isset($_GET['channelId'])) {
 $channel_id = $_GET['channelId'];
  // Call set_include_path() as needed to point to your client library.
require_once ('Google/src/Google_Client.php');
require_once ('Google/src/contrib/Google_YouTubeService.php');

  /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
  Google APIs Console <http://code.google.com/apis/console#access>
  Please ensure that you have enabled the YouTube Data API for your project. */
  $DEVELOPER_KEY = ‘API Key';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  $youtube = new Google_YoutubeService($client);
 // print_r($youtube);

try {
	
    $searchResponse = $youtube->channels->listChannels('id,snippet,statistics', array(
 'id'=>$channel_id;
   ));

     $result = '<h1>Channel Details </h1>';
				$result .= '<img src="'.$searchResponse['items'][0]['snippet']['thumbnails']['medium']['url'].'">';
				$result .= '<br/>Channel Name : ' . $searchResponse['items'][0]['snippet']['title'];
				$result .= '<br/>Total View of Channel : ' . $searchResponse['items'][0]['statistics']['viewCount'];
				$result .= '<br/>Total Comment of Channel : ' . $searchResponse['items'][0]['statistics']['commentCount'];
				$result .= '<br/>Total no. of video in Channel : ' . $searchResponse['items'][0]['statistics']['videoCount'];	
echo '<div>'.$result.'</div>';				

   } catch (Google_ServiceException $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>
<link href="//www.w3resource.com/includes/bootstrap.css" rel="stylesheet">
<style type="text/css">
body{margin-top: 50px; margin-left: 50px}
</style>
</head>
<body>
<form method="GET">
<div>
    Enter Your YouTube Channel ID <input type="search" id="channelId" name="channelId" placeholder="Enter Search Term">
</div>
<input type="submit" value="Search">
</form>

</body>
</html>

When you run youtube.php on localhost or server you will get all channel data and you can also download our attached Demo.

YouTube Analytics API

YouTube analytics API provides user activity metrics or dimension for a specified channel. To get data from Analytics API you must need user authentication will ask for accessing and managing channel data. Dimension are like filteringto channel data, such as on which date user activity occurred or how much male or female were located on particular channel or video. Metrics are individual measurement of user activity includes things like video count, likes dislike.To find details of channel using analytics API follow these steps:

1.    In credentials section of developer console you will have following page as shown below. Click on OAuth Client Id to generate client id and secret key.

2.    Enter your Product name and other details like product logo url, home page url as shown below :

3.    After that it will ask for application type ,select web application and enter your redirect url wherever you want to redirect it  as shown below:

4.    Download library from librariesfolder of attached demo and create fileindex.php file and put following code will get all channel details. Here you have to put your Client and secret Key of yourApp.

<?php
//require_once ('libraries/Google/Client.php');
// Call set_include_path() as needed to point to your client library.

require_once ('libraries/Google/Client.php');
require_once ('libraries/Google/Service.php');
require_once ('libraries/Google/Resource.php');
require_once ('libraries/Google/Model.php');
require_once ('libraries/Google/Collection.php');

require_once ('libraries/Google/Service/YouTube.php');
require_once ('libraries/Google/autoload.php');
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google Developers Console <https://console.developers.google.com/>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'Client ID'; // Application Client Id
$OAUTH2_CLIENT_SECRET = 'Secret Key'; // Application Secret Key

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
  FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}
echo '<pre>';
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
    // Call the channels.list method to retrieve information about the
    // currently authenticated user's channel.
    $channelsResponse = $youtube->channels->listChannels('id,snippet,contentDetails,statistics,status', array(
      'mine' => 'true',
    ));


	       $result = '<h1>Channel Details </h1>';
				$result .= '<img src="'.$channelsResponse['items'][0]['snippet']['thumbnails']['medium']['url'].'">';
				$result .= '<br/>Channel Name : ' . $channelsResponse['items'][0]['snippet']['title'];
				$result .= '<br/>Total View of Channel : ' . $channelsResponse['items'][0]['statistics']['viewCount'];
				$result .= '<br/>Total Comment of Channel : ' . $channelsResponse['items'][0]['statistics']['commentCount'];
				$result .= '<br/>Total no. of video in Channel : ' . $channelsResponse['items'][0]['statistics']['videoCount'];	
echo '<div>'.$result.'</div>';


  } 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()));
  }

  $_SESSION['token'] = $client->getAccessToken();
} else {
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}
?>

<!doctype html>
<html>
<head>
<title>My Uploads</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>

Now run your index.php on localhost or server will get all channel data. You can also download our attached demo.

If you have any query regarding YouTube API , feel free to ask us in comment section.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments