My favorites | English | Sign in

YouTube APIs and Tools

YouTube logo

Developer's Guide: PHP

The YouTube Data API allows client applications to retrieve and update YouTube content in the form of Google Data API feeds. Your client application can use the YouTube Data API feeds to fetch, search and update videos, comments, responses, playlists, user profiles and user contacts as well as query for videos that match particular criteria.

In addition to providing some background on the capabilities of the YouTube Data API, this document provides examples for interacting with the API using the PHP Client Library. You can download the client library as a standalone release (distributed by Zend) or as part of the Zend Framework. If you need help setting up the PHP client library, the Getting Started Guide is the place to look. If you're interested in understanding more about the underlying protocol used by the PHP client library to interact with YouTube, see the Developer's Guide protocol page.

The PHP Client Library is by no means the only way to use the YouTube Data API with PHP. There are other great resources out there, for example, see this developerWorks article detailing how to use the API with SimpleXML.

Contents

About this document

Audience

This document is intended for programmers who want to write client applications that can interact with YouTube using the PHP client library. It provides a series of examples of basic data API interactions.

For YouTube Data API reference information, see the reference guide.

This document assumes that you understand the general ideas behind the Google Data APIs protocol, and that you know PHP.

For reference information about the PHP classes and methods, see the client library's API guide.

Document structure

This document contains the following sections:

  • The Authentication section describes the two different authentication methods available for associating API operations with a specific user account. This section also outlines the differences between authentication for the YouTube Data API and other Google Data APIs. Throughout this document, the explanations of specific API functions will clearly indicate whether the function requires user authentication. In general all requests that modify video or feed data need to be authenticated. Read-only requests to public videos do not require authentication.

  • The Understanding video feeds and entries section provides a sample API response and explains how to extract information about a single video from a list of videos or a set of search results. This section also explains how to access meta-data about a specific video entry. Finally, this section explains the mechanism for updating an individual video entry.

  • The Retrieving and searching for videos section explains how to fetch specific lists of videos. Among these lists are several types of standard feeds (such as 'top-rated videos' or 'most-viewed' videos). Other lists of videos include videos uploaded by a specific user and lists of videos related to a particular video. This section also explains how to use the API to let users search through YouTube's video library by specific search terms or categories.

  • The Uploading videos section briefly explains two ways that you can allow users to upload videos to YouTube from your application. Additionally, this section also explains how to upload videos as responses to other videos.

  • The Updating and deleting videos section describes how to use the API to update information about a YouTube video. It also describes how a video can be removed using the API.

  • The Using community features section describes API functions that allow your users to interact with YouTube videos. These functions explain requests for posting a rating, comment, video response or complaint to an existing video. You can also use the API to retrieve lists of video comments or video responses or to delete a video response.

  • The Saving and collecting videos section explains how to use the API to access, create and update favorite videos, video playlists and subscriptions to YouTube channels. It also shows how to modify video playlists and favorites by adding and removing videos.

  • The Enabling user interaction section explains how to use the API to retrieve and update user profiles. This section also explains how to retrieve, add, update and delete user contacts as well as how to retrieve, send and delete messages.

Getting started

Requirements

To use the PHP client library, you must be running PHP >= 5.1.4. You also need to be using Zend_Gdata >= 1.7.0, which is distributed as part of the Zend Framework. See the Getting Started Guide for more information on configuring your environment.

The snippets of sample code below can be copied/pasted into your code and modified to fit your needs. There is also a sample application distributed with the client library which covers many of the API operations. The code is located in the /demos/YouTubeVideoApp folder.

Before you can perform any operations with the YouTube Data API, you must initialize a Zend_Gdata_YouTube object, as shown below. Please note that all actions aside from retrieving public content will require authentication.

<?php
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();

For authenticated functionality you will also need to include the one of the following helper classes, pending on whether you plan to use ClientLogin or AuthSub (see the authentication section below for more detail).

Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); 

Most of the method examples in this guide operate upon an instance of Zend_Gdata_YouTube.

Note: The contents of the Zend library directory must be in your PHP include_path.

Authentication

The PHP client library can be used to work with either public or private feeds. Public feeds are read-only and do not require any authentication. Private feeds require that you authenticate to the YouTube servers. Additionally, you will need to sign up for a YouTube Developer Key. Authentication can be performed via ClientLogin, which uses username/password authentication or via AuthSub proxy authentication.

AuthSub authentication for web applications

AuthSub proxy authentication is used by web applications which need to authenticate their users to YouTube/Google accounts. The operator does not need access to the username and password for the YouTube user — only special AuthSub tokens are required.

When the user first visits your application, they have not yet been authenticated with Google's services. In this case, you need to provide them with a link directing the user to Google to authenticate your request for access to their YouTube account. The Zend Framework PHP Google Data client library provides a function to generate this URL. The code below sets up a link to the AuthSubRequest page.

// start a new session 
session_start();

function getAuthSubRequestUrl()
{
  $next = 'http://www.example.com/welcome.php';
  $scope = 'http://gdata.youtube.com';
  $secure = false;
  $session = true;
  return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}

The code above generates a URL which requests a token from Google's YouTube service. Notice the parameters sent to the getAuthSubRequestUrl method:

  • $next — the URL of the page that Google should redirect the user to after authentication.
  • $scope — indicating the scope of feeds that the application can access.
  • $secure — indicating that the token returned will be unregistered.
  • $session — indicating this token can be exchanged for a multi-use (session) token later.

The URL will look something like this:

https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fgdata.youtube.com&session=1&secure=0&next=http%3A%2F%2Fwww.example.com%2Fwelcome.php

The user will then follow the link to Google's site and authenticate to their Google account. Once they return to your application's $next URL, the one-time token will be sent along with the redirect: http://www.example.com/welcome.php?token=DQAADKEDE.

For security, this token is single-use only, so now we need to exchange this single-use token for a session token. The following code snippet shows how to upgrade the token.

$sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);

In this snippet, the $_GET['token'] variable contains the value from the token query parameter in the URL. This token value represents a single-use AuthSub token. Since we specified $session = true in the getAuthSubRequestUrl function above, this token can be exchanged for an AuthSub session token. as is being done in the code above with the call to getAuthSubSessionToken

The function below performs performs all of these requests. It first checks whether a session token has already been set. If not, it will build an authentication url using the getAuthSubRequestUrl function described earlier. If a single-use token has been found in the URL string ($_GET['token']), it will upgrade it to a session token.

function getAuthSubHttpClient()
{
    if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
        echo '<a href="' . getAuthSubRequestUrl() . '">Login!</a>';
        return;
    } else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
      $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
    }

    $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
    return $httpClient;
}

You can then create a fully authenticated YouTube service object by passing in your $httpClient to the constructor of the Zend_Gdata_YouTube service object, along with your YouTube developer key, your application's identified and your client ID. The developer key is necessary if you plan to make any write requests to the API. The application ID and the client ID identify your application for logging and debugging purposes.

$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

This fully authenticated service object can then be used to perform all further requests with the YouTube API. AuthSub session tokens will not expire unless you specifically issue a request to revoke them or the user decides to revoke access by visiting the Authorized Sites page.

ClientLogin authentication for installed applications

ClientLogin authentication is used in installed applications that can either store or query your user for their username and password. To use this form of authentication, call the static getHttpClient method of the Zend_Gdata_ClientLogin class, specifying the email and password of the user, on whose behalf your application is sending the query. Please note that you must also pass in the URL specified below to authenticate. For example:

$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
                                          $username = 'myuser@gmail.com',
                                          $password = 'mypassword',
                                          $service = 'youtube',
                                          $client = null,
                                          $source = 'MySource', // a short string identifying your application
                                          $loginToken = null,
                                          $loginCaptcha = null,
                                          $authenticationURL);

Once the credentials have been set, the $httpClient object can be used to authenticate all further requests to the Zend_Gdata_YouTube service object. Ensure that you also pass your developer key and client ID if you wish to make write requests to the API:

$developerKey = 'ABC123 ... ';
$applicationId = 'Video uploader v1';
$clientId = 'My video upload client - v1';

$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

Note: Please refer to the developer's guide for more detailed information about the AuthSub and ClientLogin mechanisms.

Understanding video feeds and entries

The YouTube Data API provides several video feeds that represent lists of videos, such as standard feeds, uploads, subscriptions, and favorites. The URL for each feed is documented in the reference guide.

Displaying a feed of videos

Many feeds in the YouTube API consist of video entries. These feeds can most simply be modeled as Zend_Gdata_YouTube_VideoFeed objects, each containing a number of Zend_Gdata_YouTube_VideoEntry objects. Each video entry corresponds to exactly one video on YouTube and contains information about the video.

The basic structure of retrieving a list of videos is to construct a URL to a video feed and then process the entries one at a time, similar to the following code:

function getAndPrintVideoFeed($location = Zend_Gdata_YouTube::VIDEO_URI)
{
  $yt = new Zend_Gdata_YouTube();
  $videoFeed = $yt->getVideoFeed($location);
  foreach ($videoFeed as $videoEntry) {
    printVideoEntry($videoEntry); // this function is documented fully here
  }
}

The Retrieving and searching for videos section details many common feed URLs and how to retrieve various video feeds.

Retrieving a specific video entry

You can retrieve just the information for a specific video entry if you know its video ID. The entry URL is based on the video ID:

http://gdata.youtube.com/feeds/api/videos/videoID

The following code retrieves a VideoEntry corresponding to video on YouTube:

$yt->getVideoEntry('the0KZLEacs');

Video entry contents

There are many pieces of meta-data that can be retrieved from a VideoEntry object, such as thumbnails, player URLs, and video duration. The following code demonstrates how to get at some of this information. The PHP client library abstracts most of this functionality by mapping XML elements into PHP classes. Most of the important information about a VideoEntry entry is available from the children of the media:group element, which descends from VideoEntry. That XML element is mapped to the MediaGroup object and is retrievable either by calling $videoEntry->getMediaGroup() or $videoEntry->mediaGroup. We have added many helper methods to the client library that facilitate easy access to the child elements of mediaGroup and can be called directly from the VideoEntry object. An example of such a method is $videoEntry->getVideoTitle().

function printVideoEntry($videoEntry) 
{
  // the videoEntry object contains many helper functions that access the underlying mediaGroup object
  echo 'Video: ' . $videoEntry->getVideoTitle() . "\n";
  echo 'Video ID: ' . $videoEntry->getVideoId() . "\n";
  echo 'Updated: ' . $videoEntry->getUpdated() . "\n";
  echo 'Description: ' . $videoEntry->getVideoDescription() . "\n";
  echo 'Category: ' . $videoEntry->getVideoCategory() . "\n";
  echo 'Tags: ' . implode(", ", $videoEntry->getVideoTags()) . "\n";
  echo 'Watch page: ' . $videoEntry->getVideoWatchPageUrl() . "\n";
  echo 'Flash Player Url: ' . $videoEntry->getFlashPlayerUrl() . "\n";
  echo 'Duration: ' . $videoEntry->getVideoDuration() . "\n";
  echo 'View count: ' . $videoEntry->getVideoViewCount() . "\n";
  echo 'Rating: ' . $videoEntry->getVideoRatingInfo() . "\n";
  echo 'Geo Location: ' . $videoEntry->getVideoGeoLocation() . "\n";
  
  // see the paragraph above this function for more information on the 'mediaGroup' object
  // here we are using the mediaGroup object directly to its 'Mobile RSTP link' child
 foreach ($videoEntry->mediaGroup->content as $content) {
    if ($content->type === "video/3gpp") {
      echo 'Mobile RTSP link: ' . $content->url . "\n";
    }
  }
  
  echo "Thumbnails:\n";
  $videoThumbnails = $videoEntry->getVideoThumbnails();

  foreach($videoThumbnails as $videoThumbnail) {
    echo $videoThumbnail['time'] . ' - ' . $videoThumbnail['url'];
    echo ' height=' . $videoThumbnail['height'];
    echo ' width=' . $videoThumbnail['width'] . "\n";
  }
}

Note: For more information on how to generate the required information for embedding a video with player in your page please refer to the protocol guide.

Retrieving and searching for videos

Retrieving standard feeds

The YouTube Data API currently provides standard feeds of videos for various criteria. These feeds are site-wide, not user specific. The URLs of all standard feeds start with http://gdata.youtube.com/feeds/api/standardfeeds/, followed by the feed's identifier. Here is a table of the available feeds:

Feed NameFeed Identifier
Most Viewedmost_viewed
Top Ratedtop_rated
Recently Featuredrecently_featured
Watch On Mobilewatch_on_mobile
Most Discussedmost_discussed
Top Favoritestop_favorites
Most Linkedmost_linked
Most Respondedmost_responded
Most Recentmost_recent

Note: You can also retrieve locale-specific standard feeds by specifying a localeID in the format: http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID. For example, the most viewed videos in Japan would be: http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_viewed. For a complete list of supported localeIDs, please refer to the reference guide.

The following example shows how to fetch and print these standard feeds, using the YouTube::getVideoFeed() method.

The URL for some of these feeds may be defined constants and some can be retrieved by helper methods, but you can also construct the URLs manually, using the values defined in the reference guide. Note that your Zend_Gdata_YouTube service object does not need to be authenticated to retrieve standard feeds.

function getAndPrintStandardFeeds() 
{
  // constructing the URL manually
  $YOUTUBE_GDATA_SERVER = 'http://gdata.youtube.com';
  $STANDARD_FEED_PREFIX = $YOUTUBE_GDATA_SERVER . '/feeds/api/standardfeeds/';
  $TOP_RATED_FEED = $STANDARD_FEED_PREFIX . 'top_rated';
  getAndPrintVideoFeed($TOP_RATED_FEED);

  // URL as a constant in Zend_Gdata_YouTube
  getAndPrintVideoFeed(Zend_Gdata_YouTube::STANDARD_TOP_RATED_URI);

  // using helper method
  $yt = new Zend_Gdata_YouTube();
  printVideoFeed($yt->getTopRatedVideoFeed());

  // choosing the time period for a standard feed
  $yt = new Zend_Gdata_YouTube();
  $query = $yt->newVideoQuery(Zend_Gdata_YouTube::STANDARD_TOP_RATED_URI);
  $query->setTime('today');
  
  // reusing the getAndPrintVideo feed function defined earlier
  getAndPrintVideoFeed($query);
}

A Zend_Gdata_VideoFeed object is a collection of Zend_Gdata_VideoEntry objects. The following helper functions print out details of videos returned in a feed:

function printVideoFeed($videoFeed) 
{
  $count = 1;
  foreach ($videoFeed as $videoEntry) {
    echo 'Entry # ' . $count . "\n";
    printVideoEntry($videoEntry);
    echo "\n";
    $count++;
  }
}

Retrieving videos uploaded by a specific user

Each YouTube user has an associated video feed corresponding to the videos he or she has uploaded, at http://gdata.youtube.com/feeds/api/users/username/uploads. The following code demonstrates how to fetch and display a user uploads feed:

function getAndPrintUserUploads($userName)                    
{     
  $yt = new Zend_Gdata_YouTube();
  printVideoFeed($yt->getuserUploads($userName));
}  

Note: You may also use the string 'default' in place of $userName to retrieve videos for the currently authenticated user.

Retrieving related videos

To retrieve related videos, pass the video id of the Video_Entry object to the Zend_Gdata_YouTube object's getRelatedVideoFeed method. This retrieves a VideoFeed object containing related entries.

$relatedVideosFeed = $yt->getRelatedVideoFeed($originalVideo->getVideoId());

Searching for videos

The YouTube Data API lets you request a set of entries that match specified criteria, such as requesting video entries published by a particular author, by video format or containing a particular keyword. To do this, you create a VideoQuery object with your particular search criteria and pass it to the YouTube::getVideoFeed() method.

For example, to perform a keyword query with results ordered by view count, use the setVideoQuery, setOrderBy, and setRacy methods of the VideoQuery object. The following code snippet prints the titles and summaries of all videos matching a given keyword, ordered by view count.

function searchAndPrint($searchTerms = 'funny')
{
  $yt = new Zend_Gdata_YouTube(); 
  $query = $yt->newVideoQuery();
  $query->setOrderBy('viewCount');
  $query->setVideoQuery($searchTerms);
  $videoFeed = $yt->getVideoFeed($query);
  printVideoFeed($videoFeed, 'Search results for: ' . $searchTerms);
}

Note: Restricted content (racy) is excluded by default. To include it, add a call to setRacy('include').

The Query class and subclasses like VideoQuery, are responsible for constructing feed URLs. The VideoQuery shown above constructs a URL equivalent to the following:

http://gdata.youtube.com/feeds/api/videos?vq=searchTerms&orderby=viewCount

Here are some of the most common VideoQuery methods for setting search parameters:

setAuthor
Sets the author of the entry. Author is synonymous with YouTube username.
setFormat
Specifies a video format. Accepts numeric parameters to specify one of two kinds of RTSP streaming URLs for mobile video playback or a HTTP URL to the embeddable Flash player.
setRacy
Indicates whether restricted content should be included in the results. Accepts only two parameters: 'include' or 'exclude'.
setMaxResults
Sets the maximum number of entries to return at one time.
setStartIndex
Sets the 1-based index of the first result to be retrieved (for paging).
setOrderBy
Sets the order in which to list entries, such as by RELEVANCE, VIEW_COUNT, UPDATED, or RATING.
setTime
Sets a time period to limit standard feed results to: TODAY, THIS_WEEK, THIS_MONTH, or ALL_TIME.
setVideoQuery
Sets a search query term. Searches for the specified string in all video metadata, such as titles, tags, and descriptions.

If you would like to set a parameter which doesn't have acorresponding helper method in the VideoQuery class, you can set a custom parameter by calling $query->setParam('name', 'value') method. For more information about query parameters, see the YouTube Data API Reference Guide and the Google Data APIs Reference Guide.

Searching with categories and keywords

You can restrict search results to show only videos that match a given set of categories and keywords. The reference guide describes how to specify both predefined YouTube categories and user-defined keywords which are also known as tags.

The following code demonstrates how to search using keywords (tags) by changing the search terms to lowercase.

Note: Since some words (such as "comedy") can be both a YouTube category and a keyword, category and keyword queries use the convention that a capitalized word ("Comedy") denotes a YouTube category, while a lowercase word ("comedy") denotes a keyword.

function searchAndPrintVideosByKeywords($searchTermsArray)
{
  $yt = new Zend_Gdata_YouTube(); 
  $query = $yt->newVideoQuery();
  $query->setOrderBy('viewCount');
  $query->setRacy('include');
  $keywordQuery = '';
  foreach ($searchTermsArray as $searchTerm) {
    $keywordQuery .= strtolower($searchTerm) . '/';
  }
  $query->setCategory($keywordQuery);
  $videoFeed = $yt->getVideoFeed($query);
  printVideoFeed($videoFeed, 'Search results for keyword search:');
}

Note: Please refer to the Browsing with Categories and Keywords section of our Protocol Guide for more detailed information.

Searching by developer tags

Developer Tags are additional, hidden keywords that a developer may use to tag their uploaded content. These keywords will not be visible to the public and may be used to retrieve videos. To search for videos by a specific developer tag, send a general YouTube Data API search request and be sure to specify the category scheme and the developer tag that videos must match. To access videos by developer tag, your client does not need to be authenticated, but your developer key must be set in the header. You can retrieve a feed of videos matching to your developer tag ('your_tag_here' in our example) from the URL below:

$devTagUrl = "http://gdata.youtube.com/feeds/api/videos/-/%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007%2Fdevelopertags.cat%7Dyour_tag_here";
// obtain a feed with videos matching the provided developer tag
$yt->getVideoFeed($devTagUrl);

Uploading videos

Please make sure to review the diagrams in the protocol guide for a high-level overview of the upload process. Uploading videos can be done in one of two ways: either by uploading the video directly or by sending just the video meta-data and having a user upload the video through an HTML form.

Direct upload

In order to upload a video, you must first construct a new VideoEntry object and specify some required members. The following example shows uploading the Quicktime video "mytestmovie.mov" to YouTube with the following properties:

PropertyValue
TitleMy Test Movie
CategoryAutos
Keywordscars, funny
DescriptionMy description
Filenamemytestmovie.mov
File MIME typevideo/quicktime
Video private?false
Video location37,-122 (lat,long)
Developer Tagsmydevelopertag, anotherdevelopertag

The code below creates a blank VideoEntry to be uploaded. A Zend_Gdata_App_MediaFileSource object is then used to hold the actual video file. Unde the hood, the Zend_Gdata_YouTube_Extension_MediaGroup object is used to hold all of the video's meta-data. Our helper methods detailed below allow you to just set the video meta-data without having to worry about the media group object. The $uploadUrl is the location where the new entry gets posted to. This can be specified either with the $userName of the currently authenticated user, or, alternatively, you can simply use the string 'default' to refer to the currently authenticated user.

$yt = new Zend_Gdata_YouTube($httpClient);
// create a new Zend_Gdata_YouTube_VideoEntry object
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

// create a new Zend_Gdata_App_MediaFileSource object
$filesource = $yt->newMediaFileSource('mytestmovie.mov');
$filesource->setContentType('video/quicktime');
// set slug header
$filesource->setSlug('mytestmovie.mov');

// add the filesource to the video entry
$myVideoEntry->setMediaSource($filesource);

$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
$myVideoEntry->setVideoCategory('Comedy'); // Note that category must be a valid YouTube category !

// set keywords, please note that this must be a comma separated string
// and that each keyword cannot contain whitespace
$myVideoEntry->setVideoTags('cars, funny');

// optionally set some developer tags (see Searching by Developer Tags for more details)
$myVideoEntry->setVideoDeveloperTags(array('mydevelopertag', 'anotherdevelopertag'));

// optionally set the video's location
$yt->registerPackage('Zend_Gdata_Geo');
$yt->registerPackage('Zend_Gdata_Geo_Extension');
$where = $yt->newGeoRssWhere();
$position = $yt->newGmlPos('37.0 -122.0');
$where->point = $yt->newGmlPoint($position);
$myVideoEntry->setWhere($where);

// upload URI for the currently authenticated user
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';

// try to upload the video, catching a Zend_Gdata_App_HttpException if available
// or just a regular Zend_Gdata_App_Exception
try {
  $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
  echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
    echo $e->getMessage();
}

Note: To upload videos as private, simply use: $myVideoEntry->setVideoPrivate(); prior to performing the upload. You can use $videoEntry->isVideoPrivate() to check whether an entry is private or not.

Browser-based upload

Browser-based uploading is performed almost identically to direct uploading, except that you do not attach a MediaFileSource object to the VideoEntry you are constructing. Instead you simply submit all of your video's meta-data to receive back a token element which can be used to construct an HTML upload form.

$yt = new Zend_Gdata_YouTube($httpClient);
// create a Zend_Gdata_YouTube_VideoEntry
$myVideoEntry= new Zend_Gdata_YouTube_VideoEntry();

$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
$myVideoEntry->setVideoCategory('Comedy'); // Note that category must be a valid YouTube category !
$myVideoEntry->SetVideoTags('cars, funny');

$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];

The above code prints out a link and a token that is used to construct an HTML form to display in the user's browser. A simple example form is shown below with $tokenValue representing the content of the returned token element, as shown being retrieved from $myVideoEntry above. In order for the user to be redirected to your website after submitting the form, make sure to append a $nextUrl parameter to the $postUrl above, which functions in the same way as the $next parameter of an AuthSub link. The only difference is that here, instead of a single-use token, a status and an id variable are returned in the URL.

// place to redirect user after upload
$nextUrl = 'http://www.example.com/youtube_uploads';

// build the form
$form = '<form action="'. $postUrl .'?nexturl='. $nextUrl .
        '" method="post" enctype="multipart/form-data">'. 
  	'<input name="file" type="file"/>'. 
  	'<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
  	'<input value="Upload Video File" type="submit" />'. 
  	'</form>';
// assuming that $nextUrl was http://www.example.com/youtube_uploads
http://www.example.com/youtube_uploads?status=200&id=JPF-DXF7hzc

The status parameter returns the HTTP transaction status of the upload transaction. The id parameter returns the YouTube video id that was assigned to the uploaded video.

Checking upload status

After uploading a video, it will immediately be visible in an authenticated user's uploads feed. However, it will not be public on the site until it has been processed. Videos that have been rejected or failed to upload successfully will also only be in the authenticated user's uploads feed. The following code checks the status of a VideoEntry to see if it is not live yet or if it has been rejected.

// check if video is in draft status
try {
  $control = $videoEntry->getControl();
} catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
}
if ($control instanceof Zend_Gdata_App_Extension_Control) {
  if ($control->getDraft() != null && $control->getDraft()->getText() == 'yes') {
    $state = $videoEntry->getVideoState();
    if ($state instanceof Zend_Gdata_YouTube_Extension_State) {
      print 'Upload status: '. $state->getName() .' '.  $state->getText();
    } else {
      print "Not able to retrieve the video status information yet. Please try again shortly.\n";
    }
  }
}

As described in the note above, to check whether a video is private, simply use the $videoEntry->isVideoPrivate() helper method.

Updating and deleting videos

Updating video information

To update video meta-data, simply update the VideoEntry object and then use the Zend_Gdata_YouTube service's updateEntry method. Note that since updateEntry issues an http PUT request, you must use the video entry's "edit" link as the location. The code below demonstrates how to update a video's title and then how to obtain the video's 'edit' link to send the update to:

$videoEntry->setVideoTitle('A new title');
$putUrl = $videoEntry->getEditLink()->getHref();
$yt->updateEntry($videoEntry, $putUrl);

Deleting a video

Deleting a video is as simple as retrieving the uploads feed for the authenticated user and invoking the delete() method on the Zend_Gdata_YouTube service object, passing in the VideoEntry to be deleted.

$yt->delete($videoEntryToDelete);

Using community features

Adding a rating

To rate a video, simply add a Rating object to a VideoEntry and POST it to the rating link of that VideoEntry. The code below shows how to give a rating of 2 to a video entry. Ratings can range from 1 to 5 inclusive.

// $yt needs to be a fully authenticated Zend_Gdata_YouTube service object

$videoEntryToRate->setVideoRating(2);
$ratingUrl = $videoEntryToRate->getVideoRatingsLink()->getHref();

try {
  $ratedVideoEntry = $yt->insertEntry( $videoEntryToRate, $ratingUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
  echo $httpException->getRawResponseBody();
}

Comments

Retrieving comments for a video

Given a VideoEntry object, you can retrieve and print a feed containing the comments for the video using the following code:

getAndPrintCommentFeed($videoEntry->videoId);

function getAndPrintCommentFeed($videoId)
{
  $yt = new Zend_Gdata_YouTube();
  $commentFeed = $yt->getVideoCommentFeed($videoId);
  printCommentFeed($commentFeed);
}

function printCommentFeed($commentFeed) 
{
  $count = 1;
  foreach ($commentFeed as $commentEntry) {
    echo 'Entry # ' . $count . "\n";
    printCommentEntry($commentEntry);
    echo "\n";
    $count++;
  }
}

function printCommentEntry($commentEntry) 
{
  echo 'Comment: ' . $commentEntry->title->text . "\n";
  echo "Full text: " . $commentEntry->content->text . "\n";
  echo "Author: " . $commentEntry->author[0]->name->text . "\n";
}

Adding a comment

To add a new comment, simpy use the Zend_Gdata_YouTube service object.

$newComment = $yt->newCommentEntry();
$newComment->content = $yt->newContent()->setText('new comment');

// Assuming we have a valid $videoEntry that we want to comment on,
// retrieve the post url for the comment feed
$commentFeedPostUrl = $videoEntry->getVideoCommentFeedUrl();
$updatedVideoEntry = $yt->insertEntry($newComment, $commentFeedPostUrl, 'Zend_Gdata_YouTube_CommentEntry');

Video Responses

Retrieving video responses for a video

Each video entry in a video feed can have an associated video response feed, which is itself a video feed. This code demonstrates how to retrieve and print information about the video responses for a given VideoEntry:

function getAndPrintVideoResponses($videoEntry)
{
  $responsesFeedUrl = $videoEntry->getVideoResponsesLink()->getHref();
  getAndPrintVideoFeed($responsesFeedUrl); 
}

In this example, we are reusing the getAndPrintVideoFeed() function. In this case, the feed URL isn't manually constructed, but is retrieved dynamically by invoking VideoEntry::getVideoResponsesLink()->getHref(). For more information about how you can retrieve feeds without having to know their URLs, see Navigating between feeds in the reference guide.

Adding video responses

After retrieving a video response link, as demonstrated in the previous section, you can POST a VideoEntry corresponding to a video that you would like to flag as being a video response to the original video.

$yt->insertEntry($videoResponseEntry, $responsesFeedUrl);

Note: Video responses must be approved by the video's owners to appear on YouTube.

Deleting video responses

If you own the video that was responded to, you can delete individual video responses. The snippet below demonstrates how to delete a video response:

// first obtain the URL for the response feed
// assuming that $yt is a fully authenticated service object
$videoThatHasResponses = $yt->getVideoEntry('abc123');
$responseFeedUrl = $videoThatHasResponses->getVideoResponsesLink()->getHref();

$idOfVideoResponseToBeDeleted = 'xyz123';
$yt->delete($responseFeedUrl . '/' . $idOfVideoResponseToBeDeleted);

Flagging a video

Adding a complaint about a video is done through POSTing an Atom entry to the complaints link of the VideoEntry object. The below code shows how to flag a video.

$complaintUrl = $badVideoEntry->getVideoComplaintsLink()->getHref();
$complaintEntry = $yt->newEntry();
$newComplaint->content = $yt->newContent()->setText('This video is inapproriate.');

// then use the $yt service to insert the entry
try {
  $yt->insertEntry($complaintEntry, $complaintUrl);
} catch (Zend_App_Exception $e) {
  print $e->getMessage();
}

Saving and collecting videos

Favorite videos

Retrieving a user's favorite videos

YouTube users can choose to mark videos they watch as favorites. The general location for a user's favorite feed is the following URL.

http://gdata.youtube.com/feeds/api/users/username/favorites

To retrieve a user's favorite videos, simply request a feed from the Zend_Gdata_YouTube service object. The returned feed is a regular video feed, containing VideoEntry objects.

$favoritesFeed = $yt->getUserFavorites($userName);

Note: Alternatively, you may pass in the string default to retrieve favorites for the currently authenticated user.

Adding a favorite

To add a favorite video use the Zend_Gdata_YouTube service object's insertEntry method to post your new favorite (a regular Zend_Gdata_YouTube_VideoEntry) to the user's favorite feed.

$yt->insertEntry($newFavoriteVideoEntry, $favoritesFeed);

Deleting a favorite

To delete a favorite, simply use the delete() method on the Zend_Gdata_YouTube_VideoEntry object. Be sure to retrieve the favorite from the actual user's favorite feed. Otherwise you will delete the actual video entry.

$favoriteVideoToBeDeleted->delete();

Playlists

Each YouTube user has an associated playlists feed which is a list of links to a feed containing the videos in each playlist.

Retrieving user playlists

To fetch a list of all of a user's playlists by hand, you would use the following URL:

http://gdata.youtube.com/feeds/api/users/username/playlists

Note: Alternatively, you may pass in the string default to retrieve favorites for the currently authenticated user.

function getAndPrintPlaylistListFeed($userName, $showPlaylistContents)
{
  $yt = new Zend_Gdata_YouTube();
  $playlistListFeed = $yt->getPlaylistListFeed($userName);
  printPlaylistListFeed($playlistListFeed, $showPlaylistContents);
}

function printPlaylistListFeed($playlistListFeed, $showPlaylistContents)
{
  $count = 1;
  foreach ($playlistListFeed as $playlistListEntry) {
    echo 'Entry # ' . $count . "\n";
    printPlaylistListEntry($playlistListEntry, $showPlaylistContents);
    echo "\n";
    $count++;
  }
}

Retrieving playlist information

Given a PlaylistListEntry, as retrieved in the previous example, you can fetch and print the actual playlist using the following code:

function printPlaylistListEntry($playlistListEntry, $showPlaylistContents = false)
{
  echo 'Playlist: ' . $playlistListEntry->title->text . "\n";
  echo "\tDescription: " . $playlistListEntry->description->text . "\n";
  if ($showPlaylistContents === true) {
    getAndPrintPlaylistVideoFeed($playlistListEntry, "\t\t");
  }
}

function getAndPrintPlaylistVideoFeed($playlistListEntry) 
{
  $yt = new Zend_Gdata_YouTube();
  $playlistVideoFeed = $yt->getPlaylistVideoFeed($playlistListEntry->getPlaylistVideoFeedUrl());
  foreach ($playlistVideoFeed as $playlistVideoEntry) {
    printVideoEntry($playlistVideoEntry);
  }
}

The function printPlaylistListEntry() takes the optional boolean parameter showPlaylistContents; if that parameter is true, the list of videos in each playlist are also included in the output, using the functions defined in the next section.

Adding a playlist

To add a new playlist, simply use the Zend_Gdata_YouTube service object to create one and then post it to the user's playlist URL.

$newPlaylist = $yt->newPlaylistListEntry();
$newPlaylist->description = $yt->newDescription()->setText('description of my new playlist');
$newPlaylist->title = $yt->newTitle()->setText('title of my new playlist');
// post the new playlist
$postLocation = 'http://gdata.youtube.com/feeds/api/users/default/playlists';
try {
  $yt->insertEntry($newPlaylist, $postLocation);
} catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
}

Updating a playlist

To update a playlist, simply modify the retrieved Zend_Gdata_YouTube_PlaylistListEntry object and then use the save() method to save your changes.

$playlistToBeUpdated->description->setText('new description for my playlist');
$playlistToBeUpdated->save();

Add video to playlist

You can add a video to a playlist by using a VideoEntry object. The below code retrieves a VideoEntry with a known entry ID and then adds it to the playlist corresponding to the PlaylistLinkEntry. Since a position is not specified, the new video is added to the end of the playlist.

$postUrl = $playlistToAddTo->getPlaylistVideoFeedUrl();
// video entry to be added
$videoEntryToAdd = $yt->getVideoEntry('4XpnKHJAok8');

// create a new Zend_Gdata_PlaylistListEntry, passing in the underling DOMElement of the VideoEntry
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());

// post
try {
  $yt->insertEntry($newPlaylistListEntry, $postUrl);
} catch (Zend_App_Exception $e) {
  print $e->getMessage();
}

Edit video position on playlist

You can modify the position each video in a playlist by updating the PlaylistVideoEntry object for the video and calling its update method.

// get a Zend_Gdata_PlaylistVideoEntry from the feed generated by $yt->getPlaylistVideoFeedUrl
$playlistVideoEntryToBeModified->setPosition($yt->newPosition(2));

// update by putting the new entry to the entry's edit link
$yt->updateEntry($playlistVideoEntryToBeModified, $playlistVideoEntryToBeModified->getEditLink()->getHref());

Remove video from playlist

To remove a video from a playlist, use the delete() method of the PlaylistListEntry

$playlistListEntryToBeDeleted->delete();

Deleting a playlist

To delete a playlist, simply use the delete() method on the Zend_Gdata_YouTube_PlaylistListEntry object.

$playlistListEntryToBeDeleted->delete();

Subscriptions

To fetch a list of the channels, searches, and favorites that a given user is subscribed to, use the following URL:

http://gdata.youtube.com/feeds/api/users/username/subscriptions

Note: Alternatively, you may pass in the string default to retrieve favorites for the currently authenticated user.

Retrieving user subscriptions

The following code demonstrates how to retrieve and print the list of SubscriptionEntry objects for a given user:

function getAndPrintSubscriptionFeed($userName) 
{
  $yt = new Zend_Gdata_YouTube();
  // obtain a user's subscription feed. Alternatively you can use the string 'default' 
  // to retrieve subscriptions for the currently authenticated user
  $subscriptionFeed = $yt->getSubscriptionFeed($userName);
  printSubscriptionFeed($subscriptionFeed);
}

function printSubscriptionFeed($subscriptionFeed)
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $subscriptionFeed->title->text;
  }
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
  foreach ($subscriptionFeed as $subscriptionEntry) {
    echo 'Entry # ' . $count . "\n";
    printSubscriptionEntry($subscriptionEntry);
    echo "\n";
    $count++;
  }
  echo "</pre>\n";
}

function printSubscriptionEntry($subscriptionEntry)
{
  $type = 'unknown';
  $subscriptionFeedLinkMap = array(
    'query' => 'http://gdata.youtube.com/schemas/2007#video.query',
    'favorites' => 'http://gdata.youtube.com/schemas/2007#user.favorites',
    'channel' => 'http://gdata.youtube.com/schemas/2007#user.uploads' 
    );
  echo 'Subscription: ' . $subscriptionEntry->title->text . "\n";
  
  // look at the category property to to determine the type of subscription,
  // which is currently one of: query, favorites, channel
  foreach ($subscriptionEntry->category as $category) {
    if ($category->scheme == 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat') {
    $type = $category->term;
  }
        }
  echo "\tType: " . $type . "\n";
  echo "\tURL: ";
  
  // use the map defined above to fine the appropriate feedLink, depending on 
  // what type of subscription entry was passed
  $feedLink = $subscriptionEntry->getFeedLink($subscriptionFeedLinkMap[$type]);
  if ($feedLink !== null) {
    echo $feedLink->href;
  }
  echo "\n";
}

Adding a subscription

You can create a new subscription by inserting a new SubscriptionEntry into the authenticated user's subscriptions feed. The following code subscribes the authenticated user to the "GoogleDevelopers" channel.

$newSubscription = $yt->newSubscriptionEntry();
$newSubscription->extensionElements = array($yt->newUsername('GoogleDevelopers'));
$subscriptionTypesSchema = 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat';
$newSubscription->category = array($yt->newCategory('channel', $subscriptionTypesSchema));
$subscriptionsFeedUrl = 'http://gdata.youtube.com/feeds/api/users/'. $userName .'/subscriptions';
// and then post using $yt->insertEntry
try {
  $yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

You can also subscribe to the favorites of the "GoogleDevelopers" user:

$newSubscription = $yt->newSubscriptionEntry();
$newSubscription->extensionElements = array($yt->newUsername('GoogleDevelopers'));
$subscriptionTypesSchema = 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat';
$newSubscription->category = array($yt->newCategory('favorites', $subscriptionTypesSchema));
$subscriptionsFeedUrl = 'http://gdata.youtube.com/feeds/api/users/default/subscriptions';
// and then post using $yt->insertEntry
try {
  $yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

Lastly, you can also subscribe to specific search terms. Here we are subscribing to a query for videos about "puppies".

$newSubscription = $yt->newSubscriptionEntry();
// create a yt:querystring extension element to indicate a search for 'puppies'
$ytQuerystringValue = 'puppies';
$ytQuerystringSchema = 'http://gdata.youtube.com/schemas/2007';
$subscriptionTypesSchema = 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat';

$newSubscription->extensionElements = array(
  new Zend_Gdata_App_Extension_Element('queryString', 'yt', $ytQuerystringSchema, $ytQuerystringValue)
);
$newSubscription->category = array(
  $yt->newCategory('query', $subscriptionTypesSchema)
);

// and then post using $yt->insertEntry
$subscriptionsFeedUrl = 'http://gdata.youtube.com/feeds/api/users/default/subscriptions';
try {
  $yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

Note: Please note that this functionality will be abstracted in future version of the PHP client library. We will provide a helper method to automatically generate and set the yt:querystring extension element.

Deleting a subscription

To delete a user subscription, simply call delete() on the SubscriptionEntry object:

$subscriptionEntryToBeDeleted->delete();

Enabling user interaction

User Profiles

Retrieving a user's profile

To fetch a user's YouTube profile by hand, you would use the following URL:

http://gdata.youtube.com/feeds/api/users/username

You can retrieve and print a user's profile using the following code:

function getAndPrintUserProfile($userName) 
{
  $yt = new Zend_Gdata_YouTube();
  $userProfileEntry = $yt->getUserProfile($userName);
  $displayTitle = $userProfileEntry->title->text;
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
  echo 'Username: ' . $userProfileEntry->getUsername() . "\n";
  echo "\tAge: " . $userProfileEntry->getAge() . "\n";
  echo "\tGender: " . $userProfileEntry->getGender() . "\n";
  echo "\tRelationship: " . $userProfileEntry->getRelationship() . "\n";
  echo "\tBooks: " . $userProfileEntry->getBooks() . "\n";
  echo "\tCompany: " . $userProfileEntry->getCompany() . "\n";
  echo "\tHobbies: " . $userProfileEntry->getHobbies() . "\n";
  echo "\tHometown: " . $userProfileEntry->getHometown() . "\n";
  echo "\tLocation: " . $userProfileEntry->getLocation() . "\n";
  echo "\tMovies: " . $userProfileEntry->getMovies() . "\n";
  echo "\tMusic: " . $userProfileEntry->getMusic() . "\n";
  echo "\tOccupation: " . $userProfileEntry->getOccupation() . "\n";
  echo "\tSchool: " . $userProfileEntry->getSchool() . "\n";
  echo "</pre>\n";
}

Note: Please note that the string default can be used in place of a username to mean "the currently authenticated user". The client library makes use of overloaded magic methods available only in PHP 5.2. If you are using PHP 5.1, you will need to modify the calls above. In that case, something like $userProfileEntry->getAge() will need to be changed to $userProfileEntry->getAge()->getTitle().

Contacts

The list of contacts for a given user can be retrieved from the following URL:

http://gdata.youtube.com/feeds/api/users/username/contacts

Retrieving user contacts

The following code demonstrates how to retrieve and print the list of contacts for a given user:

function getAndPrintContactsFeed($userName) 
{
  $yt = new Zend_Gdata_YouTube();
  $contactsFeed = $yt->getContactsFeed($userName);
  printContactsFeed($contactsFeed);
}

function printContactsFeed($contactsFeed)
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $contactsFeed->title->text;
  }
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
  foreach ($contactsFeed as $contactsEntry) {
    echo 'Entry # ' . $count . "\n";
    printContactsEntry($contactsEntry);
    echo "\n";
    $count++;
  }
  echo "</pre>\n";
}

function printContactsEntry($contactsEntry)
{
  echo 'Contact: ' . $contactsEntry->title->text . "\n";
  foreach ($contactsEntry->category as $category) {
    if ($category->scheme == 'http://schemas.google.com/g/2005#kind') {
      $type = $category->term;
    }
  }
  echo "\tType: " . $type . "\n";
}

Adding a contact

To add a new contact as a Friend use the insertEntry method of the Zend_Gdata_YouTube service object.

$newContact = $yt->newContactEntry();
$newContact->username = $yt->newUsername('newContactsUsername');
$newContact->category = array($yt->newCategory('http://gdata.youtube.com/schemas/2007#friend', 
                                               'http://schemas.google.com/g/2005#kind'));
$yt->insertEntry($newContact, $contactFeedUrl);

Accepting/rejecting a contact

You can accept or reject a contact by updating the status of the corresponding ContactEntry.

To accept a request:

$contactEntry->setStatus($yt->newStatus('accepted'));
$contactEntry->save();

To reject a request simply pass the value 'rejected' to the status of the ContactEntry.

Deleting a contact

To delete a contact, simply call the delete() method on the ContactEntry object.

$contactToBeDeleted->delete();

Messages

Messages can be sent between YouTube users that have mutually accepted each other into their contacts. All messages sent through the API must include a VideoEntry.

Retrieving user messages

To retrieve the contents of a user's inbox, make an authenticated request to the user's inbox URL:

http://gdata.youtube.com/feeds/api/users/username/inbox

The below example prints out the contents of the authenticated user's inbox by fetching a Zend_Gdata_YouTube_InboxFeed, which contains a Zend_Gdata_YouTube_InboxEntry for each message in the user's inbox.

// Assuming that $yt is a valid and authenticated Zend_Gdata_YouTube object
$inboxFeed = $yt->getInboxFeedForCurrentUser();

foreach($inboxFeed as $inboxEntry) {
  echo "Message title: " . $inboxEntry->getTitle()->text . "\n";

  $authors = $inboxEntry->getAuthor();
  $author = $authors[0];
  echo "Sent from: " . $author->name->text . "\n":

  // Since each message contains a video, we can request similar
  // metadata, such as ratings, etc.
  echo "Average rating: " . $inboxEntry->getRating()->average . "\n";
}

Sending a message to a user

All messages must contain a YouTube video. To use the sendVideoMessage method, you must either pass in a valid Zend_Gdata_YouTube_VideoEntry object, or the Id string of a valid video.

// Assuming that $yt is a valid and authenticated Zend_Gdata_YouTube object
$body = 'Here is a video that you may find interesting';
$receipientUserName = 'foobar'; # Note this must be a valid username.
$videoId = 'ylLzyHk54Z0'; # This must be the Id of a valid video.

// Note that the second parameter could also take a valid Zend_Gdata_YouTube_VideoEntry object.
try {
  $sentMessage = $yt->sendVideoMessage($body, null, $videoId, 'gdpython');
} catch (Zend_Gdata_App_HttpException $e) {
  print 'Something went wrong ' . $e->getMessage() . "\n";
  print 'Raw HTTP response ' . $e->getRawResponseBody() . "\n";
}

Note: The recipient of the message must be an accepted contact of the sender of the message.

Deleting a message

To delete a message, simply call delete() on the entry.

$videoMessageEntryToBeDeleted->delete();

Conclusion

Questions? Feedback? Notice a typo in this doc? Let us know in the discussion forum. Happy coding!

Back to top