YouTube Analytics API php Samples

后端 未结 3 1407
别跟我提以往
别跟我提以往 2021-01-06 13:04

I want to make this YouTube Analytics Request with the PHP Client Libary

https://www.googleapis.com/youtube/analytics/v1/reports  
?ids=channel==CHANNELID
         


        
3条回答
  •  长情又很酷
    2021-01-06 13:35

    This collects day-by-day analytics over the last 30 days and then inserts it into a database. Here's the code:

    set_include_path(get_include_path() . PATH_SEPARATOR . '/home/google-api-php-client/src');
    
    require_once('Google/autoload.php');
    
    require_once 'Google/Client.php';
    require_once 'Google/Service/YouTube.php';
    
    session_start();
    
    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setAccessType("offline");
    $client->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtubepartner-channel-audit', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtubepartner'));
    $client->setDeveloperKey($key);
    
    $analytics = new Google_Service_YouTubeAnalytics($client);
    
    $ids = 'channel==' . $channel_url . '';
    $end_date = date("Y-m-d"); 
    $start_date = date('Y-m-d', strtotime("-30 days"));
    $optparams = array(
    'dimensions' => 'day',
    );
    
    $metric = 'views';
    
    try{
    
    $api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
    
    foreach ($api->rows as $r) {
        $date = $r[0];
        $views = $r[1];
    
    $stmt = $db->prepare("INSERT INTO test (date,views,channel_url) VALUES (:date,:views,:channel_url)");
    $stmt->execute([':date' => $date, ':views' => $views, ':channel_url' => $channel_url]);
    }
    }catch (Google_Service_Exception $e) {
        echo sprintf('

    A service error occurred: %s

    ', htmlspecialchars($e->getMessage())); }

提交回复
热议问题