YouTube API | Getting the analytics and putting the data into a chart

Hello, i’m working on a dashboard to show YouTube users analytics. I have the authentication method and I can retrieve the data all through php, but i’m not very good with getting the JSON data and putting it into a chart like chart.js. This might be a JS question, but this is also a PHP question as well so I decided to put it into the PHP section.

<?php set_time_limit(0);
	ob_start();	
	
	/******Change these ********/
	$client_id="xxxx";
	$email_address="xxxxxx";
	$client_secret="xxxxx";
	$redirect_uris="xxxxxx";
	$javascript_origins="xxxxxx";
	
	
	
	
	function get_access_token($authentication_code,$client_id,$client_secret,$redirect_uris){
	$url = "https://accounts.google.com/o/oauth2/token";
 	$post="code={$authentication_code}&client_id={$client_id}&client_secret={$client_secret}&redirect_uri={$redirect_uris}&grant_type=authorization_code";
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
     curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');  
     curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');  
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");  
	 $st=curl_exec($ch);  
	 return $result=json_decode($st,TRUE);	 
	 }
	 
	 function get_curl($url){
		  $ch = curl_init();
		  $headers = array("Content-type: application/json");
		 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	     curl_setopt($ch, CURLOPT_URL, $url);
		 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
	     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
	     curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');  
	     curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');  
	     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
	     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");   
		 $st=curl_exec($ch);  
		return $result=json_decode($st,TRUE);
	 }
	 function get_id($url){
		  $ch = curl_init();
		  $headers = array("Content-type: application/json");
		 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	     curl_setopt($ch, CURLOPT_URL, $url);
		 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
	     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
	     curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');  
	     curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');  
	     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
	     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");   
		 $st=curl_exec($ch);  
		return $st;
	 }
	 
	 

if(isset($_GET['code'])){
	$authentication_code=$_GET['code'];
}

if ($access_token=='' && $authentication_code!=''){
	/******Get The authorization Code/Access Token******/
	$result=get_access_token($authentication_code,$client_id,$client_secret,$redirect_uris);
	/***Take access token, also there is the expiration duration*****/
	$access_token=$result['access_token'];

	$refresh_token=$result['refresh_token'];
}
	
if(!$access_token){
	$auth_url="https://accounts.google.com/o/oauth2/auth";
	$message = "<form id=form-login action='{$auth_url}' method=get>
	<input type=hidden name=client_id value=$client_id>
	<input type=hidden name=redirect_uri value=$redirect_uris>
	<input type=hidden name=scope value=\"https://www.googleapis.com/auth/yt-analytics.readonly https://www.googleapis.com/auth/youtube.readonly\">
	<input type=hidden name=response_type value=code>
	<input type=hidden name=access_type value=offline>
	<button class=\"btn btn-effect-ripple btn-lg btn-primary\" type=submit>Apply Now</button></form>";
} else {
	
	$end_date=date('Y-m-d');
	$start_date=date('Y-m-d',strtotime("-1 months"));
	 
	 $gcid="https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&access_token={$access_token}";
	 $channelfind=get_id($gcid);

	$s="https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date={$start_date}&end-date={$end_date}&metrics=views,comments,likes&dimensions=day&sort=day&access_token={$access_token}";
	 $view_data=get_curl($s);

	 
	
	 $total_view=0;
	 foreach($view_data['rows'] as $v){
	 	$total_view+=$v[1];
	 }	//MONTHLY VIEWS NUMBER

	 $channelid = explode('id": "', $channelfind);
	 $channelid = explode('"
  }
 ]
}', $channelid[1]);
	 $channelid = $channelid[0]; //CHANNELID
	 
	 echo "Monthly Views: ".$total_view." <br />Channel ID: ".$channelid."<br />";
	 echo "access toke:".$access_token."";

	}

	echo $message 

	 ?>

This is the code i’m using to retrieve the channel id and monthly views. I want to retrieve month to month statistics for views, subscribers, likes, comments, etc. I can do that, but the problem is putting it into a js chart like chart.js. Would I need it to put it in an array in PHP or what would I need to do. I’ve googled and googled, but nothing specific to this question has come up. I appreciate any help I can get, thank you.

I’d say (though it’s based on some very old code, not in PHP, and using a different chart API) that the next part of your code, instead of the echo statements at the end, would be to use a combination of include and echo to create a dynamic web page with the chart in it.

First, create yourself a static html page with javascript code that displays the chart in the format you want it to. Hard-code the data in the chart until you have it working. Then, have your PHP code create that same html / javascript code once it has the results from your call to the google API. You will be able to see which parts of the final page don’t change (which you can incorporate into the output using include/require) and those that do, which you can output using echo.

Well what I figured out is I can put the chart into a script tags and echo the data into the data part of the chart once I have it parsed, but now my problem is getting it parsed because i’m not very good at that.

Well, have a stab at it and post the code if you have further problems.

Ok I did, but only one point is displaying. This is just a bs chart I got to try to populate the chart to see if it worked. I guess I need to loop it, but don’t know how to go about that

<script>
  var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
    datasets: [{
      label: 'Views',
      data: [<?php echo $v[1]; ?>],
      backgroundColor: "rgba(153,255,51,0.4)"
    }, {
      label: 'Comments',
      data: [<?php echo $v[2]; ?>],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]
  }
});
  </script>

OK, but in your initial code you have a loop

	 foreach($view_data['rows'] as $v){
	 	$total_view+=$v[1];
	 }	//MONTHLY VIEWS NUMBER

Depending on what the data format that comes back from the API is, you could use for() or foreach() to iterate through the loop and insert the data points.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.