Skip to content

Instantly share code, notes, and snippets.

@tszym
Created July 3, 2014 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tszym/5c605ea829cea5772db8 to your computer and use it in GitHub Desktop.
Save tszym/5c605ea829cea5772db8 to your computer and use it in GitHub Desktop.
Youtube Analytics API - Get metrics
<?php
// ...
if ($client->getAccessToken()) {
// Create analytics service object.
$youtube = new Google_Service_YouTubeAnalytics($client);
try {
// Here we query the API
$analyticsResponse = $youtube->reports->query('channel==UCKVMqeVtKOKxIIqPX84_MKA', '2014-06-25', '2014-06-29',
'views,likes,shares,dislikes,averageViewDuration');
$htmlBody = '';
$htmlBody .= '<h3>Analytics</h3><ul>';
// And we exploit the results
for ($i=0, $length=count($analyticsResponse['columnHeaders']); $i<$length; $i++) {
$htmlBody .= sprintf('<li><strong>%s:</strong> %s</li>',
$analyticsResponse['columnHeaders'][$i]['name'],
$analyticsResponse->rows[0][$i]);
}
$htmlBody .= '</ul>';
} 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()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
// ...
}
?>
<!doctype html>
<html>
<head>
<title>Search Youtube</title>
<meta charset="UTF-8">
</head>
<body>
<?php echo $htmlBody; ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment