순지난의 좋은선물



CATEGORY

분류 전체보기 (62)
아이폰 (5)
안드로이드 (2)
PHP (7)
IT 팁 (13)
snoopy.class (8)
sencha (0)
PhoneGap (0)
jQuery (2)
리눅스 (4)
즐겨찾기 (2)
js (1)
Html &CSS (6)
wowza (1)
모바일웹 (1)
ajax (0)
mysql (1)
apps (5)
corona sdk (1)

RECENT ARTICLE

RECENT COMMENT

RECENT TRACKBACK

ARCHIVE

LINK



  1. 2011.06.23
    정규식 기본 정리 1
  2. 2011.06.18
    YouTube APIs and Tools
  3. 2011.06.16
    에디트플러스 텍스트파일 중복제거하기
  4. 2011.06.16
    동영상을 스트림이 끝나면 발생되는 이벤트 잡아내기
  5. 2011.06.16
    CSS 예제 사이트 모음
  6. 2011.06.16
    meta Element 란 무엇인가? 종류안내
  7. 2011.06.13
    URL Snooper로 동영상 주소 찾는 방법
  8. 2011.06.11
    preg_match_all to match <img> tags
  9. 2011.06.11
    파일서버에 업로드, Network Drive에 저장
  10. 2011.06.10
    CSS 예제 사이트 모음
^abc 
abc 로 시작

abc$
abc 로 끝남

^abc$
abc 로 시작 끝

abc
abc 를 포함

ab*
a 뒤에 없거나 b 1개 이상

ab+
a 뒤에 b만 1개 이상

ab?
a 뒤에 없거나 b 1개

ab{4}
abbbb

ab{4,}
a 뒤에 b 가 최소 4개 이상

ab{5,7}
a 뒤에 b가 5~7 개

ab{0,}
ab* 와 동일

ab{1,}
ab+ 와 동일

ab{0,1}
ab? 와 동일

a(bc)*
a 뒤에 bc 가 없거나 1개 이상 a(bc){0,} 동일

a(bc){5,7}
a 뒤에 bc 가 5~7 개

a|b 
a 또는 b

(a|bc)d
ad 또는 bcd

(a|b)*c
a 또는 b 가 없거나 1개 이상 있고 c

[0-9]
0~9 또는 숫자

a.
a 와 어떤 문자 1개

a.[0-9]
a 와 어떤문자 다음 숫자

^a{3}$
aaa

^.
어떤 문자 1개 로 시작

^.{5}
어떤 문자 5개 로 시작

^.{5}$
5 개 문자

^[0-9]
숫자로 시작

^[a-z]
영문자 소문자로 시작 

^[a-zA-Z]
영문자로 시작

[^0-9]
숫자가 없음

[^a-zA-Z]
영문자가 없음

$
$

[*]
*

^[1-9][0-9]*$
1 ~ 9로 시작하고 0 ~ 9로 끝남

^(0|[1-9][0-9]*)$
0 또는 1 ~ 9로 시작하고 0 ~ 9로 끝남

^[0-9]+(.[0-9]+)?$
0 ~ 9 로 시작 . 과 0 ~ 9 로 끝나거나 없을 수 있음 ( 1.0 가능 10. 불가능)

^[0-9]+(.[0-9]{2})?$
0 ~ 9 로 시작 . 뒤에 최소 2자리 숫자 또는 없음 ( 1.00 가능 1.0 불가능 1 가능)
And
http://code.google.com/intl/ko/apis/youtube/2.0/developers_guide_php.html#Retrieving_Video_Feed

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 to fetch video feeds, comments, responses, and playlists, as well as query for videos that match particular criteria. You can also use the API to make authenticated requests to modify this information and to upload new video content to the site.

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.

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, such as 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, including expected latencies for data updates, please 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 retrieve 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 metadata about a specific video entry.

  • The Retrieving and searching for videos section explains how to fetch a list of videos. The YouTube Data API defines several types of standard feeds, such as top-rated or most-viewed videos. This section explains how also to retrieve a list of videos uploaded by a specific user or a list of related videos. Finally, this section explains how to use the API to let users search through YouTube's video library for videos matching 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. This section also explains how to let users delete videos from your application. These solutions are explained in more detail in the Protocol Guide. You may need to let users upload videos to use certain other API functions. For example, the API provides a function for adding a video response to a video. If the user is uploading a new video as a video response, then your client will need to follow the video uploading instructions to add the video to YouTube before identifying the new video as a response.

  • 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 explains 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

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

The snippets of sample code in this document can be copied and pasted into your code and then modified to fit the needs of your application. In addition, the client library is distributed with a sample application that demonstrates many 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 in the following example. (Most of the method examples in this guide also operate on an instance of Zend_Gdata_YouTube.) Please note that all API operations that do not involve 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();

To use API functionality that requires user authentication, you will also need to include the one of the following helper classes, depending on whether you plan to use AuthSub or ClientLogin authentication.

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

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

Authentication

The PHP client library can be used to retrieve public feeds or to execute authenticated operations. All public feeds are read-only and do not require any authentication. Authenticated operations, on the other hand, include the retrieval of private feeds, such as a user's inbox feed, as well as write, upload, update and delete operations. You will need to sign up for a developer key to be able to execute authenticated operations.

You can authenticate requests using either AuthSub proxy authentication or ClientLogin username/password authentication.

Please see the Protocol Guide and the authentication documentation for Google Data APIs for more information about AuthSub and ClientLogin.

AuthSub for web applications

AuthSub proxy authentication enables web applications to authenticate users to their YouTube accounts without having to access the user's YouTube username and password. You should use AuthSub authentication if you are building a web application that will let users link videos, comments, ratings, contacts or other information to their own YouTube accounts.

When a user visits your application for the first time, the user will not yet have been authenticated to use your application to access Google services. To authenticate the user, you need to display a link that points the user to a Google login page. After the user logs in, she can authorize your application to use the API to access her account. Google will then redirect the user back to a URL specified in your authentication request. The redirect will include a single-use token that your application can use to execute an API operation.

The following sample code constructs an AuthSub request URL. The code retrieves a nonsecure token that will be exchanged for a session token, which can then be used multiple times.

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

You pass the following parameters to the getAuthSubRequestUrl method:

  • The $next parameter contains the URL to which the user will be redirected after logging in to YouTube.

  • The $scope parameter identifies the service that the user is enabling your site to access on his behalf. The value of this parameter must be http://gdata.youtube.com.

  • The $secure parameter contains a boolean value (0 or 1) that indicates whether the authentication service will return a secure or nonsecure token. Secure tokens are issued only to websites that have registered with Google, and video upload requests that use a secure token must be digitally signed. Please see the Google AuthSub documentation for more details about secure tokens.

  • The $session parameter contains a boolean value (0 or 1) that indicates whether the single-use authentication token that the authentication service returns can be exchanged for a session token, which can be used multiple times. Set this variable to 1 to indicate that the single-use token can be exchanged for a session token. Please see the Google AuthSub documentation for an explanation of how to request a session token.

The AuthSub request URL will have the following format. (Your request URLs may specify different parameter values.)

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

After the user logs in via YouTube's authentication service, YouTube will redirect the user back to the URL identified in the next parameter in your AuthSub request. The redirect contains a single-use authentication token, which is identified by the token parameter in the URL as shown. If the value of the session parameter in your AuthSub request was 1, then you can exchange the single-use token for a session token by submitting a getAuthSubSessionToken request. The following URL shows how the token parameter will appear in the redirect to your site.

http://www.example.com/welcome?token=DQAADKEDE

Your application can set an authentication cookie before the user has the opportunity to link to the AuthSub request URL. The cookie can then enable your application to recognize the authenticated user after the AuthSub authentication page redirects the user to your web page.

Upgrading to a session token

As noted above, the token that you receive in the redirect URL is a single-use token. You can exchange the single-use token for a session token, which does not expire, by submitting a getAuthSubSessionToken request. The function below demonstrates how to make this exchange. If no session token has been set, but a single-use token exists, the function exchanges the single-use token for a session token. If no single-use token exists and no session token exists, the function builds an authentication URL using the getAuthSubRequestUrl function described earlier.

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 create a fully authenticated YouTube service object by passing the $httpClient object to the Zend_Gdata_YouTube service object's constructor. You will also need to pass an ID for your application, your YouTube developer key and your client ID to the constructor. The developer key is only necessary if your application lets users upload videos, perform API write operations such as creating playlists or adding comments, or retrieve private feeds, such as a user's inbox feed. The application ID and the client ID identify your application for logging and debugging purposes.

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

You can then use the fully authenticated service object to perform all further YouTube API requests. An AuthSub session token will not expire unless you specifically issue a request to revoke it. For example, your application could obtain a token at the beginning of a user's session and then revoke the token at the end of the session. A user can also revoke access to your application (and its associated token) through the Authorized Sites page in the user's YouTube account.

ClientLogin for installed applications

ClientLogin authentication is used in installed applications that store the user's email address (username) and password. To use ClientLogin authentication, call the static getHttpClient method of the Zend_Gdata_ClientLogin class, specifying the email and password of the user associated with the authentication request. Please note that your authentication request must also pass the authentication URL specified in the sample code.

Note: ClientLogin authentication should not be used in Web applications, which should use AuthSub authentication instead.

The following code demonstrates how to use ClientLogin to authenticate a user.

$authenticationURL= 'https://www.google.com/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 handle all further requests to the Zend_Gdata_YouTube service. To be able to perform uploads and any kind of write operations, such as adding comments or creating playlists, you also need to provide your developer key and client ID when you initialize the Zend_Gdata_YouTube object. Please visit http://code.google.com/apis/youtube/dashboard to obtain a developer key and client ID.

$developerKey = 'ABC123 ... '; 
$applicationId
= 'Video uploader v1'; 
$clientId = 'My video upload client - v1'; 
 
$yt
= new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

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

Setting the API version

As of version 1.7.4 of the PHP Client Library, the version 2 specific functionality has not yet been enabled by default. You can use the setMajorProtocolVersion function to set a version for either a service class, a feed or an entry. A version 2 specific service class will always return v2 feeds and entries.

// Assuming that $yt is a valid Zend_Gdata_YouTube object 
$yt
->setMajorProtocolVersion(2);

This guide will assume that all instances of the Zend_Gdata_YouTube service object (denoted as $yt) are version 2 objects.

Note: The client library may be modified in the future so that version 2 is enabled by default.

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 favorite videos. 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 be modeled most simply as Zend_Gdata_YouTube_VideoFeed (VideoFeed) objects, each of which contains a number of Zend_Gdata_YouTube_VideoEntry (VideoEntry) objects. Each video entry corresponds to exactly one YouTube video and contains information about that video.

The following code retrieves a video feed and then prints information about each entry in the feed:

function getAndPrintVideoFeed($location = Zend_Gdata_YouTube::VIDEO_URI) 
{ 
  $yt
= new Zend_Gdata_YouTube(); 
 
// set the version to 2 to receive a version 2 feed of entries 
  $yt
->setMajorProtocolVersion(2); 
  $videoFeed
= $yt->getVideoFeed($location); 
  printVideoFeed
($videoFeed); 
} 
  
function printVideoFeed($videoFeed) 
{ 
  $count
= 1; 
 
foreach ($videoFeed as $videoEntry) { 
    echo
"Entry # " . $count . "\n"; 
   
printVideoEntry($videoEntry); 
    echo
"\n"; 
    $count
++; 
 
} 
}

The Retrieving and searching for videos section describes different types of video feeds and provides the URLs and instructions for retrieving those feeds.

Retrieving a specific video entry

Each entry in a video feed contains a link element for which the rel attribute value is self. This tag identifies the URL for a feed of information about that particular video. The URL has the following format:

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

The following code retrieves a VideoEntry object, which corresponds to a particular YouTube video, and then prints the metadata for the video:

$videoEntry = $yt->getVideoEntry('the0KZLEacs'); 
printVideoEntry($videoEntry);

Video entry contents

A VideoEntry object, which corresponds to an entry in an Atom feed, contains many different pieces of metadata about a video, ranging from video player URLs to thumbnail images to details like the video's duration and keywords.

The following code demonstrates how to print a variety of details about a video. Many important data fields for a VideoEntry object are specified by the children of the <media:group> element. In the PHP client library, that element is mapped to the Zend_Gdata_YouTube_Extension_MediaGroup (MediaGroup) object, which can be retrieved by calling either $videoEntry->getMediaGroup() or $videoEntry->mediaGroup. The client library contains many help methods that facilitate easy access to the child elements of mediaGroup and that can be called directly from the VideoEntry object. For a complete list of all of the information that a VideoEntry object contains, please refer to the <entry> tag definition in the API Reference Guide. Specifically, refer to the <entry> tag's subtags for retrieving a video entry.

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"; 
  echo
'Recorded on: ' . $videoEntry->getVideoRecorded() . "\n"; 
   
 
// see the paragraph above this function for more information on the  
 
// 'mediaGroup' object. in the following code, we use the mediaGroup 
 
// object directly to retrieve 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 about how to generate the information required to embed a video with a player in your page please refer to the protocol guide.

Determining whether a user can edit a video entry

By default, the getVideoEntry method will return a read-only video entry. If the user is authenticated and owns the video being retrieved, you can pass in true to the third parameter of the getVideoEntry method to retrieve an 'editable' video entry. You can also use the getFullVideoEntry method to retrieve editable video entries.

You can determine whether the currently authenticated user is the owner of a particular video entry by calling the getEditLink method on that entry. The sample code below demonstrates how to determine whether a video entry is editable.

if ($videoEntry->getEditLink() !== null) { 
  echo
"Video is editable by current user.\n"; 
}

Retrieving and searching for videos

Retrieving standard feeds

The YouTube Data API provides standard feeds selected based on a variety of criteria. Standard feeds are sitewide rather than user-specific. They contain lists of videos that either reflect YouTube user behavior, such as top-rated and most viewed video feeds, or were selected by YouTube staff, such as recently featured and mobile video feeds. Standard feeds are updated every few minutes.

The URLs for all standard feeds have the following format:

http://gdata.youtube.com/feeds/api/standardfeeds/FEED_IDENTIFIER

The following table lists the standard feeds available through the YouTube Data API.

Feed Name Feed Identifier
Most Viewed most_viewed
Top Rated top_rated
Recently Featured recently_featured
Watch On Mobile watch_on_mobile
Most Discussed most_discussed
Top Favorites top_favorites
Most Responded most_responded
Most Recent most_recent

You can also retrieve region-specific standard feeds and category-specific standard feeds by specifying either a regionID, a category name, or both in the feed URL. The URL for a region- and category-specific standard feed has the following format:

http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID_CATEGORY_NAME

For example, the following example shows the feed URL for a list of the top-rated comedies in Japan:

http://gdata.youtube.com/feeds/api/standardfeeds/JP/top_rated_Comedy

Please refer to the reference guide for more information about standard feeds, region-specific standard feeds and category-specific standard feeds.

The following example demonstrates how to retrieve a standard feed and print information about the videos in that feed. This example uses the YouTube::getVideoFeed() method. Note that the URLs for standard feeds may be defined constants and that some URLs may be retrieved using helper methods. You can also construct the URLs manually following the instructions above and 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 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(); 
  $yt
->setMajorProtocolVersion(2); 
 
getAndPrintVideoFeed($yt->getRecentlyFeaturedVideoFeed()); 
 
 
// choosing the time period for a standard feed 
  $yt
= new Zend_Gdata_YouTube(); 
  $yt
->setMajorProtocolVersion(2); 
  $query
= $yt->newVideoQuery(Zend_Gdata_YouTube::STANDARD_TOP_RATED_URI); 
  $query
->setTime('today'); 
 
getAndPrintVideoFeed($query); 
}

Note: If you don't want to use the helper methods, you can also use version 2 specific constants such as STANDARD_TOP_RATED_URI_V2, STANDARD_MOST_VIEWED_URI_V2, STANDARD_RECENTLY_FEATURED_URI_V2, and STANDARD_WATCH_ON_MOBILE_URI_V2.

Videos uploaded by a specific user

For each YouTube user, the YouTube Data API defines a video feed that lists the videos that the user has uploaded. The video feed for a user's uploaded videos can be retrieved from the following URL:

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

The following code demonstrates how to retrieve a feed of videos uploaded by a particular user:

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

Note: In the feed URL, you can substitute the string default instead of a username to retrieve the videos uploaded by the currently authenticated user. In this case, you would retrieve the feed located at http://gdata.youtube.com/feeds/api/users/default/uploads.

Each video entry in a video feed identifies the URL for another video feed that contains videos related to the entry, as determined by YouTube. To retrieve the related videos feed for a VideoEntry object, pass the video id of the VideoEntry object to the Zend_Gdata_YouTube object's getRelatedVideoFeed method. The following code shows how to retrieve and print information about the related videos for a particular VideoEntry.

$relatedVideosFeed = $yt->getRelatedVideoFeed($originalVideo->getVideoId()); 
foreach ($relatedVideosFeed as $relatedVideoEntry) { 
 
printVideoEntry($relatedVideoEntry); 
}

Searching for videos

The YouTube Data API lets you request a set of videos that match a particular search term. The API supports a variety of standard Google Data query parameters and custom parameters specifically related to video search. For example, you can search for videos uploaded by a particular author or videos associated with a particular YouTube category.

To execute a search request, you will create a Zend_Gdata_YouTube_VideoQuery (VideoQuery) object that specifies your search criteria and pass that object to the YouTube::getVideoFeed method.

The following example demonstrates how to perform a search query for videos that match the search term "puppy". The query specifies that the result set may include restricted content and will be ordered by view count:

function searchAndPrint($searchTerms = 'puppy') 
{ 
  $yt
= new Zend_Gdata_YouTube(); 
  $yt
->setMajorProtocolVersion(2); 
  $query
= $yt->newVideoQuery(); 
  $query
->setOrderBy('viewCount'); 
  $query
->setSafeSearch('none'); 
  $query
->setVideoQuery($searchTerms); 
 
 
// Note that we need to pass the version number to the query URL function 
 
// to ensure backward compatibility with version 1 of the API. 
  $videoFeed
= $yt->getVideoFeed($query->getQueryUrl(2)); 
 
printVideoFeed($videoFeed, 'Search results for: ' . $searchTerms); 
}

In the client library code, the Zend_Gdata_Query (Query) class and subclasses like VideoQuery are responsible for constructing feed URLs. The example above constructs the following feed URL:

http://gdata.youtube.com/feeds/api/videos?q=keyword&safeSearch=none&orderby=viewCount

Note: To exclude a search term, prepend the term with a hyphen. (This functionality is also available in the search engine on the YouTube website.) For example, to search for videos matching the word 'dog' but not the word 'skateboarding', you would use the following code:

$query->setVideoQuery('dog -skateboarding');

The following list identifies some of the most common VideoQuery methods for setting search parameters. The reference guide contains a complete list of query parameters and their definitions. Since some of these parameters are not supported in version 1 of the YouTube Data API, you must specify a version in your YouTube service class to automatically set the appropriate header for your API requests.

setAuthor
The setAuthor method sets the author of the entry.
setFormat
The setFormat method specifies a video format or a set of video formats.
setLocation
The setLocation method specifies geographic coordinates (latitude, longitude) for a specific location.
setLocationRadius
The setLocationRadius method, in conjunction with the setLocation method, defines a geographic area. Search results will include videos associated with locations in that area.
setMaxResults
The setMaxResults method sets the maximum number of entries to return at one time.
setOrderBy
The setOrderBy method sets the order in which to list entries, such as by RELEVANCE, VIEW_COUNT, UPDATED, or RATING.
setSafeSearch
The setSafeSearch method indicates amount of filtering (none, moderate or strict) that YouTube should apply to remove restricted content from search results.
setStartIndex
The setStartIndex method sets the 1-based index of the first result to be retrieved (for paging).
setTime
The setTime method sets a time period to limit standard feed results to: TODAY, THIS_WEEK, THIS_MONTH, or ALL_TIME.
setUploader
The setUploader method restricts search results to videos from YouTube Partner Program participants. The only value that this method accepts is partner.
setVideoQuery
The setVideoQuery method sets a search query term. The API will search for the specified string in all video metadata, such as titles, tags, and descriptions.

Note: To set a parameter value if the parameter does not have a corresponding helper method in the VideoQuery class, call the $query->setParam('name', 'value') method.

Searching for videos using categories and keywords

You can restrict search results to show only videos that match a given set of categories and/or keywords. The reference guide describes how to specify both predefined YouTube categories, such as "Comedy" or "Music", and user-defined keywords, which are also known as tags. Each video can have many keywords but can only be associated with one YouTube category.

Key point: Some words, such as "comedy", can be both a YouTube category and a keyword. To distinguish between categories and keywords, the API uses the convention that capitalized words (e.g. "Comedy") denote YouTube categories and lowercase words (e.g. "comedy") denote keywords.

The following code demonstrates how to search for videos in the "News" category that match the keywords "sports" and "football". The example shows how to filter search results using both categories and keywords.

function searchAndPrintVideosByKeywords($searchTermsArray) 
{ 
  $yt
= new Zend_Gdata_YouTube();  
  $query
= $yt->newVideoQuery(); 
  $query
->setOrderBy('viewCount'); 
  $query
->setRacy('include'); 
  $query
->setCategory('News/sports/football'); 
 
 
/* 
   * The following commented-out code block demonstrates how to generate  
   * the value that is passed to $query->setCategory 
   *  
   * $keywordQuery = ''; 
   * foreach ($searchTermsArray as $searchTerm) { 
   *   $keywordQuery .= strtolower($searchTerm) . '/'; 
   * } 
   * $query->setCategory($keywordQuery); 
   */
 
 
  $videoFeed
= $yt->getVideoFeed($query); 
 
printVideoFeed($videoFeed, 'Search results for keyword search:'); 
}

The previous example retrieved videos that matched the "News" category and the keywords "sports" and "football". The following example, on the other hand, retrieves videos that match the "News" category and either or both of those keywords. Note that to specify that a video must match the keyword "sports" or the keyword "football", instead of separating those two terms with a forward slash ("/") in the value passed to the $query->setCategory() function, you would separate them with %7C, which is a URL-escaped pipe character.

function searchAndPrintVideosByKeywords($searchTermsArray) 
{ 
  $yt
= new Zend_Gdata_YouTube();  
  $query
= $yt->newVideoQuery(); 
  $query
->setOrderBy('viewCount'); 
  $query
->setRacy('include'); 
  $query
->setCategory('News/sports%7Cfootball'); 
 
  $videoFeed
= $yt->getVideoFeed($query); 
 
printVideoFeed($videoFeed, 'Search results for keyword search:'); 
}

The reference guide explains how to retrieve a list of categories that can be used to classify YouTube videos. The guide also explains how to retrieve localized category lists for several languages and locales.

Searching for videos using developer tags

When a user uploads a video through your site or application, you can associate the video with developer tags that you use to identify the video. YouTube does not display developer tags to YouTube users; however, you can retrieve or update videos that match a specific developer tag.

Developer tags can only be associated with a video at the time that the video is uploaded. In addition, developer tags that are assigned when a video is uploaded cannot be altered thereafter.

Each developer tag that is associated with a video is linked to the developer key specified in the request to upload that video. To search for videos that match a particular developer tag, the search request must specify the same developer key as the original upload requests for those videos. This restriction ensures that information about videos associated with a particular developer tag is only available to the developer that assigned that tag. Search requests for videos matching a particular developer tag do not require user authentication.

The following code demonstrates how to retrieve a list of videos associated with a particular developer tag:

$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);

Paging through results

API responses contain pagination links for the previous and/or next page of entries in a feed. The following code sample demonstrates how to retrieve the previous and next pages of results for a feed:

$videoFeed = $yt->getRecentlyFeaturedVideoFeed(); 
 
// See if the feed specifies a previous page of results. 
// In this example, the following lines of code would throw an  
// exception since the $videoFeed contains the first page of results. 
try { 
  $previousFeed
= $videoFeed->getPreviousFeed(); 
} catch (Zend_Gdata_App_Exception $e) { 
  echo $e
->getMessage() . "\n"; 
} 
 
// See if the feed specifies a next page of results. 
try { 
  $nextFeed
= $videoFeed->getNextFeed(); 
} catch (Zend_Gdata_App_Exception $e) { 
  echo $e
->getMessage() . "\n"; 
}

So, for example, you could use the following code to retrieve all results for a feed. This code performs the following operations:

  1. It retrieves a feed.
  2. It prints out all of the entries in the feed.
  3. It determines whether additional results for the feed are available.
    • If additional results are available, the code returns to step 1. (At this point, the feed being retrieved in step 1 is the next page of results.) The code repeats these steps until no additional results are available.

// Note tht this works on a v1 or v2 YouTube service object 
$yt
= new Zend_Gdata_YouTube(); 
$videoFeed
= $yt->getUserUploads('GoogleDevelopers'); 
 
/** 
 * Recursive function to print an entire feed. 
 * 
 * @param Zend_Gdata_YouTube_VideoFeed $videoFeed The feed to print 
 *        in this iteration. 
 * @param integer $counter The counter to display and increment 
 *        on each printed feed entry. 
 * @return void 
 */
 
function printEntireFeed($videoFeed, $counter) { 
 
foreach($videoFeed as $videoEntry) { 
   echo $counter
. " - " . $videoEntry->getVideoTitle() . "\n"; 
   $counter
++; 
 
} 
 
 
// See whether we have another set of results 
 
try { 
   $videoFeed
= $videoFeed->getNextFeed(); 
 
} catch (Zend_Gdata_App_Exception $e) { 
   echo $e
->getMessage() . "\n"; 
   
return; 
 
} 
 
 
if ($videoFeed) { 
   echo
"-- next set of results --\n"; 
   printEntireFeed
($videoFeed, $counter); 
 
} 
} 
 
printEntireFeed
($videoFeed, 1);

In an actual implementation, you might prefer to display pagination links rather than display all feed results on a single page. Since a feed could contain dozens or hundreds of results, pagination links might contribute to a more polished user interface.

If you do display pagination links, please be careful not to expose your developer credentials in those links. For example, if you use the client and key query parameters in API requests, then the pagination links in the API response will contain those values. As such, you would not want to expose those URLs directly through your user interface.

Uploading videos

You can upload videos in one of two ways:

  • Direct uploading allows you to add videos that are in your video library to YouTube. You should choose a direct-upload implementation if you want to host or store videos uploaded through your site and also add those videos to YouTube. In a direct-uploading scenario, when a user uploads a video through your site, the video will be sent to your servers. Your application will subsequently send an API request to upload the video from your server to YouTube.

  • Browser-based uploading allows you to accept video uploads from your users without having to handle, host or proxy the actual video files. You should choose a browser-based uploading process if you do not want to host or store the uploaded video files.

You must provide the following fields for all uploaded videos:

  • Title
  • Description
  • Category
  • Keywords

Note: Uploaded videos should be visible in the authenticated user's uploads feed immediately. In addition, a newly uploaded video will typically be included in search results a couple of hours after the upload completes. However, this delay may be longer during periods of heavy API server loads. Please see the Checking upload status section for more information.

Direct upload

To upload a video, you must construct a new VideoEntry object that contains metadata about the video. The following example shows how to upload the Quicktime video "file.mov" to YouTube with the following properties:

Property Value
Title My Test Movie
Category Autos
Keywords cars, funny
Description My description
Video private? false
Developer tag mydevtag, anotherdevtag
Video location 37,-122 (lat,long)
Filename file.mov
File MIME type video/quicktime

The following code uploads the video:

// Note that this example creates an unversioned service object. 
// You do not need to specify a version number to upload content 
// since the upload behavior is the same for all API versions. 
$yt
= new Zend_Gdata_YouTube($httpClient); 
 
// create a new VideoEntry object 
$myVideoEntry
= new Zend_Gdata_YouTube_VideoEntry(); 
 
// create a new Zend_Gdata_App_MediaFileSource object 
$filesource
= $yt->newMediaFileSource('file.mov'); 
$filesource
->setContentType('video/quicktime'); 
// set slug header 
$filesource
->setSlug('file.mov'); 
 
// add the filesource to the video entry 
$myVideoEntry
->setMediaSource($filesource); 
 
$myVideoEntry
->setVideoTitle('My Test Movie'); 
$myVideoEntry
->setVideoDescription('My Test Movie'); 
// The category must be a valid YouTube category! 
$myVideoEntry
->setVideoCategory('Autos'); 
 
// Set keywords. Please note that this must be a comma-separated string 
// and that individual keywords cannot contain whitespace 
$myVideoEntry
->SetVideoTags('cars, funny'); 
 
// set some developer tags -- this is optional 
// (see Searching by Developer Tags for more details) 
$myVideoEntry
->setVideoDeveloperTags(array('mydevtag', 'anotherdevtag')); 
 
// set the video's location -- this is also optional 
$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 otherwise 
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(); 
}

To upload videos as private, use the $myVideoEntry->setVideoPrivate(); method before starting the upload. You can also use the $videoEntry->isVideoPrivate() method to check whether a video entry is a private video.

Browser-based upload

Browser-based uploading follows almost the same process as direct uploading. However, there are a few key differences:

  • When you use direct uploading, your request specifies the location of the media file source. However, when you use browser-based uploading, the video is uploaded from the user's browser to YouTube and not directly from your server. As such, with browser-based uploading you do not attach a Zend_Gdata_App_MediaFileSource (MediaFileSource) object to the VideoEntry you are constructing.

  • Browser-based uploading uses a special URL instead of the authenticated user's uploads URL:

    http://gdata.youtube.com/action/GetUploadToken
  • When you use direct uploading, YouTube returns a VideoEntry for the uploaded video. However, when you use browser-based uploading, YouTube returns a URL and upload token that you will use to build a form through which the user completes the upload process.

The browser-based uploading process has several steps:

  1. You create a VideoEntry object that only contains metadata about the video being uploaded. The metadata includes all of the fields that you would specify in the direct uploading process – e.g. title, description, category, etc. – except the location of the actual video file.

  2. You pass the VideoEntry object as a parameter to the getFormUploadToken method.

  3. YouTube returns a URL and upload token that you then use to build a form through which the user uploads the video file associated with the metadata uploaded in the previous step. The following code sample completes steps 1 through 3 of this process:

    // Note that this example creates an unversioned service object. 
    // You do not need to specify a version number to upload content 
    // since the upload behavior is the same for all API versions. 
    $yt
    = new Zend_Gdata_YouTube($httpClient); 
     
    // create a new VideoEntry object 
    $myVideoEntry
    = new Zend_Gdata_YouTube_VideoEntry(); 
     
    $myVideoEntry
    ->setVideoTitle('My Test Movie'); 
    $myVideoEntry
    ->setVideoDescription('My Test Movie'); 
    // The category must be a valid YouTube category! 
    $myVideoEntry
    ->setVideoCategory('Autos'); 
     
    // Set keywords. Please note that this must be a comma-separated string 
    // and that individual keywords cannot contain whitespace 
    $myVideoEntry
    ->SetVideoTags('cars, funny'); 
     
    $tokenHandlerUrl
    = 'http://gdata.youtube.com/action/GetUploadToken'; 
    $tokenArray
    = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl); 
    $tokenValue
    = $tokenArray['token']; 
    $postUrl
    = $tokenArray['url'];
  4. You build a standard HTML form through which the user can upload the video file. The form must follow these guidelines:

    • It must use the upload URL, which was parsed from the API response in step 3, as the value of the <form> tag's action attribute.

    • You need to add the nexturl parameter to the form's target URL. This parameter specifies the URL to which YouTube will redirect the user's browser after the user uploads the video file.

    • You must set the value of the <form> tag's enctype attribute to multipart/form-data.

    • The form must contain an <input> tag that identifies the video file, and the value of the name attribute for that tag must be file.

    • The form must contain a hidden <input> tag that specifies the token value parsed from the API response in step 3. The value of the name attribute for that tag must be token.

    The following code shows a sample form.

    // 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>';
  5. After uploading the video file, the user is redirected to the nexturl specified in your form. If the upload was successful, YouTube appends id and status parameters to the URL as shown in the following example:

    http://www.example.com/youtube_uploads?status=200&id=JPF-DXF7hzc

    If the upload was not successful, YouTube appends status and code parameters to the URL to help you diagnose the cause of the failure. The reference guide provides more information about these parameters.

Checking upload status

After a user uploads a video, it will immediately be visible in the authenticated user's uploads feed:

http://gdata.youtube.com/feeds/api/users/default/uploads

However, the video will not be publicly visible on YouTube until YouTube has finished processing the video. In addition, videos that YouTube rejected or that failed to upload successfully will only be listed in the authenticated user's uploads feed. The following code checks the status of a VideoEntry object to determine whether YouTube is still processing the video, failed to process the video, or rejected the video.

// Assuming that $videoEntry is the object that was returned during the upload 
$state
= $videoEntry->getVideoState(); 
 
if ($state) { 
  echo
'Upload status for video ID ' . $videoEntry->getVideoId() . ' is ' . 
    $state
->getName() . ' - ' . $state->getText() . "\n"; 
 
} else { 
    echo
"Not able to retrieve the video status information yet. " .  
     
"Please try again later.\n"; 
}

Note: You can also use the $videoEntry->isVideoPrivate() helper method to check whether a video is private.

Updating and deleting videos

Updating video information

To modify the metadata for a video, update the VideoEntry object and then use the Zend_Gdata_YouTube service's updateEntry method. Note that since the updateEntry method issues an HTTP PUT request to update an existing object, the request URL must be the edit link for the video. The following code demonstrates how to retrieve a video's edit link and then update the video's description.

$putUrl = $videoEntry->getEditLink()->getHref(); 
$videoEntry
->setVideoDescription('This description is better. Hurrah!'); 
$yt
->updateEntry($videoEntry, $putUrl);

Please refer to the Determining whether a user can edit a video entry section for more information about editing videos.

Deleting a video

To delete a video, invoke the delete method on the Zend_Gdata_YouTube service object, passing in the VideoEntry object that is being deleted. For example, you could retrieve the uploaded videos feed for the authenticated user and then delete a video selected by the user.

$yt->delete($videoEntryToDelete);

Note: The authenticated user must be the owner of the video that is being deleted.

Using community features

Adding a rating

A user can add a rating to a video. YouTube uses a 1-5 rating system in which 1 is the lowest rating that can be given. Users cannot update or delete ratings. Typically, a user would rate a video after watching that video.

To rate a video, insert a Rating object to the ratings feed URL for the VideoEntry that is being rated. The following code shows how to add a rating to a video:

// $yt must 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

A comment is a text response to a video. Logged-in users can add comments to a video but cannot modify or delete those comments. In addition, please note that YouTube will convert any HTML markup that appears in a comment into plain text. Typically, a user would add a comment to a video after watching that video.

Retrieving video comments

The following code demonstrates how to retrieve the comments feed URL from a VideoEntry object and then print the comments for the video.

getAndPrintCommentFeed($videoEntry->videoId); 
 
function getAndPrintCommentFeed($videoId) 
{ 
  $yt
= new Zend_Gdata_YouTube(); 
 
// set the version to 2 to retrieve a version 2 feed 
  $yt
->setMajorProtocolVersion(2); 
  $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 comment to a video, insert a Zend_Gdata_YouTube_CommentEntry (CommentEntry) object into the comments feed URL for the video. The following code demonstrates how to add a new comment for a video:

$newComment = $yt->newCommentEntry(); 
$newComment
->content = $yt->newContent()->setText('new comment'); 
 
// post the comment to the comments feed URL for the video 
$commentFeedPostUrl
= $videoEntry->getVideoCommentFeedUrl(); 
$updatedVideoEntry
= $yt->insertEntry($newComment, $commentFeedPostUrl, 
 
'Zend_Gdata_YouTube_CommentEntry');

Video Responses

Retrieving video responses for a video

A video response is a video that is associated, as a reply, with a second video. A video can be designated as a video response to exactly one other video. An authenticated user can add or delete video responses, but the user must have uploaded a video to modify that video's video response status.

Each video entry in a video feed can have an associated video response feed. That feed, which lists all of the video responses to the video described in the video entry, is itself a video feed.

The following 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);  
}

This example reuses the getAndPrintVideoFeed() function described in the Displaying a feed of videos section. In this example, the video responses feed URL is retrieved dynamically by invoking VideoEntry->getVideoResponsesLink()->getHref().

Adding a video response

To add a video response, which is identified by a VideoEntry object, insert it into the video responses feed URL for the original video. The following code demonstrates how to retrieve the video responses feed URL for a video and then add a new video response to the feed.

$responsesFeedUrl = $videoEntry->getVideoResponsesLink()->getHref(); 
$yt
->insertEntry($videoResponseEntry, $responsesFeedUrl);

Note: A video owner has the opportunity to review and approve all video responses to the owner's videos. A video response will only be included in a video responses feed if the video owner has approved the response.

Deleting a video response

The currently authenticated user can delete a video from a video responses feed if she is the owner of the video that was responded to. The following code demonstrates how to delete a video response:

// obtain the URL for the video responses feed 
// $yt must be a fully authenticated service object 
$videoThatHasResponses
= $yt->getVideoEntry('abc123'); 
$responseFeedUrl
= $videoThatHasResponses->getVideoResponsesLink()->getHref(); 
 
$idOfVideoResponseToBeDeleted
= 'xyz123'; 
$yt
->delete($responseFeedUrl . '/' . $idOfVideoResponseToBeDeleted);

Flagging a video

To post a complaint about a video, insert an Atom entry containing the complaint to the complaints link for the VideoEntry object that describes that video. The entry specifies a complaint category as well as the full text of the complaint. The following code demonstrates how to flag a video:

$complaintUrl = $badVideoEntry->getVideoComplaintsLink()->getHref(); 
$complaintEntry
= $yt->newEntry(); 
$newComplaint
->content = $yt->newContent()->setText('This video is inappropriate.'); 
 
// then use the $yt service to insert the entry 
try { 
  $yt
->insertEntry($complaintEntry, $complaintUrl); 
} catch (Zend_App_Exception $e) { 
  echo $e
->getMessage(); 
}

Saving and collecting videos

Favorite videos

Retrieving a user's favorite videos

YouTube users can choose to mark videos that they watch as favorite videos. A user's favorite videos feed can be retrieved from the following URL:

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

Note: Using the string default instead of a username retrieves the favorite videos of the currently authenticated user.

To retrieve a user's favorite videos, request a feed from the Zend_Gdata_YouTube service object as shown in the example below, which retrieves and prints a specified user's favorite videos. The returned feed is a regular video feed, which contains VideoEntry objects.

// optionally specify version 2 to retrieve a v2 feed 
$yt
->setMajorProtocolVersion(2); 
$favoritesFeed
= $yt->getUserFavorites($userName);

Adding a favorite video

To add a favorite video, use the Zend_Gdata_YouTube service object's insertEntry method to post the video, which is identified by a regular VideoEntry object, to the authenticated user's favorite videos feed.

// Either specify the URL of the favorite feed itself, or get it from the object 
$yt
->insertEntry($newFavoriteVideoEntry, $favoritesFeed->getSelfLink()->href);

Deleting a favorite video

To delete a favorite video from the currently authenticated user's favorite videos feed, call the delete method on the VideoEntry object that corresponds to the favorite video you want to delete.

$favoriteVideoEntry->delete();

Note: You must retrieve the VideoEntry object that identifies the favorite video from the authenticated user's favorite videos feed. Otherwise, your request will attempt to delete the actual video itself.

Playlists

A YouTube user's playlists feed contains a list of that user's playlists, with each feed entry corresponding to a single playlist. The client library enables you to retrieve, add, update and delete playlists. It also lets you retrieve a list of the videos in a single playlist as well as add, update or delete playlist videos. The client library uses the following objects to work with playlists:

Retrieving a user's playlists

To retrieve a feed of a particular user's playlists, you use the following URL:

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

Note: Using the string default instead of a username retrieves the profile of the currently authenticated user.

The following code demonstrates how to retrieve and print information about a particular user's playlists:

function getAndPrintPlaylistListFeed($userName, $showPlaylistContents) 
{ 
  $yt
= new Zend_Gdata_YouTube(); 
 
// optionally set version to 2 to retrieve a version 2 feed 
  $yt
->setMajorProtocolVersion(2); 
  $playlistListFeed
= $yt->getPlaylistListFeed($userName); 
  printPlaylistListFeed
($playlistListFeed, $showPlaylistContents); 
} 
 
function printPlaylistListFeed($playlistListFeed, $showPlaylistContents) 
{ 
  $count
= 1; 
 
foreach ($playlistListFeed as $playlistListEntry) { 
    echo
'Entry # ' . $count . "\n"; 
 
   
// This function is defined in the next section 
    printPlaylistListEntry
($playlistListEntry, $showPlaylistContents); 
 
    echo
"\n"; 
    $count
++; 
 
} 
}

Retrieving playlist information

The following code demonstrates how to use a PlaylistListEntry, as retrieved in the previous example, to retrieve and print information about the videos in that playlist.

// print the metadata of the playlist entry itself 
function printPlaylistListEntry($playlistListEntry, $showPlaylistContents = false) 
{ 
  echo
'Title: ' . $playlistListEntry->title->text . "\n"; 
  echo
'Description: ' . $playlistListEntry->description->text . "\n"; 
 
 
// assuming $yt is a fully authenticated service object, set the version to 2 
 
// to retrieve additional metadata such as yt:uploaded and media:credit 
  $yt
->setMajorProtocolVersion(2); 
 
  $playlistVideoFeed
= 
    $yt
->getPlaylistVideoFeed($playlistListEntry->getPlaylistVideoFeedUrl()); 
 
 
if ($showPlaylistContents === true) { 
   
foreach ($playlistVideoFeed as $playlistVideoEntry) { 
     
// Reuse the printVideoEntry function defined earlier to show video metadata 
     
printVideoEntry($playlistVideoEntry); 
   
     
// The following details are also available for playlist entries 
      echo
'Video originally uploaded on: ' . 
        $playlistVideoEntry
->getMediaGroup->getUploaded()->text . "\n"; 
   
     
// Also check the <media:credit> element to see whether the video 
     
// was uploaded by a partner. 
      $mediaCredit
= $playlistVideoEntry->getMediaGroup()->getMediaCredit(); 
     
if ($mediaCredit) { 
 
        echo
'Video originally uploaded by ' . $mediaCredit->text . "\n"; 
        echo
'Media credit role: ' . $mediaCredit->getRole() . "\n"; 
     
       
// if the yt:type attribute is present, then the video was uploaded 
       
// by a YouTube partner 
        echo
'Media credit type: ' . $mediaCredit->getYTtype() . "\n"; 
     
} 
   
} 
 
} 
}

In the sample code above, the printPlaylistListEntry() function accepts an optional boolean parameter named showPlaylistContents. If that parameter is set to true, the function will print the list of videos in the playlist in addition to the playlist title and description.

Adding a playlist

To add a new playlist, use the Zend_Gdata_YouTube service object to create the playlist and then insert it into the authenticated user's playlists feed.

$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

You can use the API to update a playlist's title, description and or public/private status. To update a playlist, modify the PlaylistListEntry object for that playlist and then call the object's save method.

The following code updates a playlist's description.

$playlistToBeUpdated->description->setText('updated playlist description'); 
$playlistToBeUpdated
->save();

Adding a video to a playlist

You can add a video to a playlist by using a VideoEntry object. The following code retrieves a VideoEntry object with a known entry ID and then adds it to the playlist corresponding to the PlaylistListEntry object. Since the request does not specify a position where the video will appear in the playlist, 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) { 
  echo $e
->getMessage(); 
}

Editing information for a playlist video

You can modify the position of 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 
// move to top of playlist by setting position to 0 
$playlistVideoEntryToBeModified
->setPosition($yt->newPosition(0)); 
 
// update by putting the new entry to the entry's edit link 
try { 
  $yt
->updateEntry($playlistVideoEntryToBeModified, $playlistVideoEntryToBeModified->getEditLink()->getHref()); 
}

Removing a video from a playlist

To remove a video from a playlist, use the delete method of the PlaylistVideoEntry.

$playlistVideoEntry->delete();

Deleting a playlist

To delete a playlist, call the delete method of the corresponding PlaylistListEntry object.

$playlistListEntry->delete();

Subscriptions

Retrieving a user's subscriptions

To fetch a list of the channels, favorite video lists and search queries that a given user has subscribed to, send a request to the following URL:

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

Note: Using the string default instead of a username retrieves the currently authenticated user's subscriptions.

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

// assuming that $yt is a fully authenticated YouTube service object 
// optionally set the version to 2 to retrieve a v2 feed 
$yt
->setMajorProtocolVersion(2); 
// enter the username of the user whose subscriptions you want to retrieve  
$subscriptionFeed
= $yt->getSubscriptionFeed($userName); 
 
// loop through feed entries and print information about each subscription 
foreach($subscriptionFeed as $subscriptionEntry) { 
  $subscriptionType
= null; 
 
// get the array of categories to find out what type of subscription it is 
  $categories
= $subscriptionEntry->getCategory(); 
 
// examine the correct category element since there are multiple 
 
foreach($categories as $category) { 
   
if ($category->getScheme() == 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat') { 
      $subscriptionType
= $category->getTerm(); 
   
} 
 
} 
 
 
switch ($subscriptionType) { 
   
case 'channel': 
      echo
'Subscription to channel: ' . $subscriptionEntry->getUsername()->text . "\n"; 
     
break; 
   
case 'query': 
      echo
'Subscription to search term: ' . $subscriptionEntry->getQueryString() . "\n"; 
     
break; 
   
case 'favorites': 
      echo
'Subscription to favorites of user ' . $subscriptionEntry->getUsername()->text . "\n"; 
     
break; 
   
case 'playlist': 
      echo
'Subscription to playlist ' . $subscriptionEntry->getPlaylistTitle() .  
       
' of user ' . $subscriptionEntry->getUsername()->text . "\n"; 
     
break; 
 
} 
}

Adding a subscription

You can create a new subscription by inserting a new Zend_Gdata_YouTube_SubscriptionEntry (SubscriptionEntry) into the authenticated user's subscriptions feed. Users can subscribe to another user's channel, another user's list of favorite videos, a playlist or a search query.

Subscribing to a channel

The following code subscribes the authenticated user to the "GoogleDevelopers" channel.

// this example assumes that $yt is a fully authenticated service object 
$subscriptionsFeedUrl
= "http://gdata.youtube.com/feeds/api/users/default/subscriptions"; 
$newSubscription
= $yt->newSubscriptionEntry(); 
 
$channel
= 'GoogleDevelopers'; 
$newSubscription
->setUsername(new Zend_Gdata_YouTube_Extension_Username($channel)); 
 
// post 
$yt
->insertEntry($newSubscription, $subscriptionsFeedUrl);
Subscribing to a list of favorite videos

The following code subscribes the authenticated user to the "GoogleDevelopers" user's list of favorite videos:

// this example assumes that $yt is a fully authenticated service object 
$subscriptionsFeedUrl
= "http://gdata.youtube.com/feeds/api/users/default/subscriptions"; 
$newSubscription
= $yt->newSubscriptionEntry(); 
 
$channel
= 'GoogleDevelopers'; 
$newSubscription
->setUsername(new Zend_Gdata_YouTube_Extension_Username($channel)); 
$newSubscription
->category = array( 
  $yt
->newCategory('favorites', 
                     
'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat')); 
 
// post 
$yt
->insertEntry($newSubscription, $subscriptionsFeedUrl);
Subscribing to a playlist

The following code subscribes the authenticated user to the Android playlist, which has the playlist ID 586D322B5E2764CF, in the 'GoogleDevelopers' channel.

// this example assumes that $yt is a fully authenticated service object 
$subscriptionsFeedUrl
= "http://gdata.youtube.com/feeds/api/users/default/subscriptions"; 
 
// since this feature is only available in version 2 of the API, 
// you need to set the protocol version to 2 
$newSubscription
->setMajorProtocolVersion(2); 
 
$newSubscription
= $yt->newSubscriptionEntry(); 
 
$channel
= 'GoogleDevelopers'; 
$newSubscription
->setUsername(new Zend_Gdata_YouTube_Extension_Username($channel)); 
$newSubscription
->category = array( 
  $yt
->newCategory('playlist', 
                     
'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat')); 
// set the id of the playlist 
$newSubscription
->setPlaylistId(new Zend_Gdata_YouTube_Extension_PlaylistId('586D322B5E2764CF')); 
 
// post 
$yt
->insertEntry($newSubscription, $subscriptionsFeedUrl);
Subscribing to a search query

The following code subscribes the authenticated user to videos that match the search term "puppies":

// this example assumes that $yt is a fully authenticated service object 
$subscriptionsFeedUrl
= "http://gdata.youtube.com/feeds/api/users/default/subscriptions"; 
$newSubscription
= $yt->newSubscriptionEntry(); 
$newSubscription
->setQueryString(new Zend_Gdata_YouTube_Extension_QueryString('puppies')); 
 
// post 
$yt
->insertEntry($newSubscription, $subscriptionsFeedUrl);

Deleting a subscription

To delete a subscription, call the delete method on the corresponding SubscriptionEntry object.

$subscriptionEntry->delete();

Enabling user interaction

Profiles

Retrieving a user's profile

To retrieve a user's profile, send a request to the following URL:

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

Note: Using the string default instead of a username retrieves the profile of the currently authenticated user.

The following code prints out a number of attributes from a specified user's profile:

function getAndPrintUserProfile($userName)  
{ 
  $yt
= new Zend_Gdata_YouTube(); 
 
 
// set protocol version to 2 to retrieve a v2 profile entry, 
 
// which contains additional information from the user's profile 
  $yt
->setMajorProtocolVersion(2); 
 
 
// enter a username or set the $userName variable to 'default' 
 
// to retrieve the currently authenticated user's profile 
  $userProfileEntry
= $yt->getUserProfile($userName); 
 
  echo $userProfileEntry
->title->text . "\n"; 
  echo
"Profile Information\n"; 
  echo
'Username: ' . $userProfileEntry->getUsername() . "\n"; 
  echo
'Profile picture url ' . $userProfileEntry->getThumbnail()->getUrl() . "\n"; 
  echo
'About me: ' . $userProfileEntry->getAboutMe() . "\n"; 
  echo
'Website (URL): ' . $userProfileEntry->getLink('related')->getHref() . "\n"; 
  echo
"Personal Details\n"; 
  echo
'Age : ' . $userProfileEntry->getAge() . "\n"; 
  echo
'Gender: ' . $userProfileEntry->getGender() . "\n"; 
  echo
'Relationship: ' . $userProfileEntry->getRelationship() . "\n"; 
  echo
'Hometown: ' . $userProfileEntry->getHometown() . "\n"; 
  echo
'Location ' . $userProfileEntry->getLocation() . "\n"; 
  echo
"Interests\n"; 
  echo
'Hobbies: ' . $userProfileEntry->getHobbies() . "\n"; 
  echo
'Books: ' . $userProfileEntry->getBooks() . "\n"; 
  echo
'Movies: ' . $userProfileEntry->getMovies() . "\n"; 
  echo
'Music: ' . $userProfileEntry->getMusic() . "\n"; 
  echo
"Jobs \ Career \ Education\n"; 
  echo
'Occupation: ' . $userProfileEntry->getOccupation() . "\n"; 
  echo
'Companies: ' . $userProfileEntry->getCompany() . "\n"; 
  echo
'School: ' . $userProfileEntry->getSchool() . "\n"; 
  echo
'Member since ' . $userProfileEntry->getPublished()->text . "\n"; 
  echo
'Last profile update on ' . $userProfileEntry->getUpdated()->text . "\n"; 
 
 
// retrieve counts of favorites, contacts, subscriptions and uploads 
 
// by examining the feedLink elements in the profile 
  echo
"Additional video count information\n"; 
  echo $userProfileEntry
->getFeedLink( 
   
'http://gdata.youtube.com/schemas/2007#user.favorites')->countHint . " favorite videos.\n"; 
  echo $userProfileEntry
->getFeedLink( 
   
'http://gdata.youtube.com/schemas/2007#user.contacts')->countHint . " user contacts.\n"; 
  echo $userProfileEntry
->getFeedLink( 
   
'http://gdata.youtube.com/schemas/2007#user.subscriptions')->countHint . " subscriptions.\n"; 
  echo $userProfileEntry
->getFeedLink( 
   
'http://gdata.youtube.com/schemas/2007#user.uploads')->countHint . " video uploads.\n"; 
 
 
// examine the yt:statistics element for further information 
  $statistics
= $userProfileEntry->getStatistics(); 
  echo
'User channel viewed ' . $statistics->getViewCount() . " times.\n"; 
  echo $statistics
->getVideoWatchCount() . " videos watched\n"; 
  echo $statistics
->getSubscriberCount() . " subscribers\n"; 
  echo
'Last login on ' . $statistics->getLastWebAccess() . "\n"; 
}

Note: The client library uses overloaded magic methods, which are only available in PHP 5.2. If you are using PHP 5.1, you will need to modify the calls in the sample code to print profile details. For example, you would need to change $userProfileEntry->getAge() to $userProfileEntry->getAge()->getTitle().

Contacts

Retrieving a user's contacts

To retrieve a list of a user's contacts, send a request to the following URL:

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

The following code demonstrates how to retrieve and print the contacts of a specified user:

function getAndPrintContactsFeed($userName)  
{ 
  $yt
= new Zend_Gdata_YouTube(); 
  $contactsFeed
= $yt->getContactsFeed($userName); 
  printContactsFeed
($contactsFeed); 
} 
 
function printContactsFeed($contactsFeed) 
{ 
  $count
= 1; 
  echo $contactsFeed
->title->text . "\n"; 
 
foreach ($contactsFeed as $contactsEntry) { 
    echo
'Entry # ' . $count . "\n"; 
    printContactsEntry
($contactsEntry); 
    echo
"\n"; 
    $count
++; 
 
} 
} 
 
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 contact, use the insertEntry method of the Zend_Gdata_YouTube service object to insert the contact to the authenticated user's contacts feed. The request can specify any number of user-defined categories to associate the contact with groups, such as "Family", "Bowling Enthusiasts," "Wizards" and so forth. The example below adds a contact with the username "GoogleDevelopers" to the "Cool Dudes" category.

$newContact = $yt->newContactEntry(); 
$newContact
->username = $yt->newUsername('GoogleDevelopers'); 
$newContact
->category =  
  array
($yt->newCategory('Cool Dudes', 
                           
'http://gdata.youtube.com/schemas/2007/contact.cat')); 
$yt
->insertEntry($newContact, $contactFeedUrl);

Accepting or rejecting a contact

You can accept or reject a contact by updating the status of the corresponding Zend_Gdata_YouTube_ContactEntry (ContactEntry) object.

The following example shows how to accept a contact:

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

The following example shows how to reject a contact:

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

Deleting a contact

To delete a contact, call the delete method on the ContactEntry that you are deleting.

$contactEntry->delete();

Messages

The API enables you to send messages between YouTube users who have mutually accepted each other as contacts. All messages sent through the API must include a VideoEntry.

Retrieving messages

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

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

The following example prints the contents of the authenticated user's inbox. It fetches a Zend_Gdata_YouTube_InboxFeed (InboxFeed), which contains a Zend_Gdata_YouTube_InboxEntry (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"; 
 
 
// See if there was a custom message body sent: 
  $body
= $inboxEntry->getSummary(); 
 
if ($body != null) { 
    echo
"Message body: " . $body->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

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

The following code sends a message containing a video to a user identified by the variable $recipientUserName:

// Assuming that $yt is a valid and authenticated Zend_Gdata_YouTube object 
$body
= 'Here is a video that you may find interesting'; 
 
$recipientUserName
= 'gdpython'; # Note this must be a valid username. 
$videoId
= 'ylLzyHk54Z0'; # This must be the Id of a valid video. 
 
// insert the message 
try { 
 
// In this example, the third parameter specifies the videoId. 
 
// Instead of specifying a videoId, you could also provide a valid 
 
// Zend_Gdata_YouTube_VideoEntry object as the value of the second parameter. 
  $sentMessage
= 
    $yt
->sendVideoMessage($body, null, $videoId, $recipientUserName); 
} catch (Zend_Gdata_App_HttpException $e) { 
  echo
'Something went wrong ' . $e->getMessage() . "\n"; 
  echo
'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, call the delete method on a MediaEntry object:

$mediaEntry->delete();

Activity feeds

Activity feeds list actions that a particular user or set of users has taken on the YouTube site. The API enables you to retrieve two types of activity feeds:

  • A user activity feed identifies actions taken by one or more users who are specified in the API request.
  • A friend activity feed identifies actions that an authenticated user's friends have recently taken on the YouTube site.

Activity feeds list the following user actions:

  • Rating a video
  • Sharing a video
  • Marking a video as a favorite
  • Commenting on a video
  • Uploading a video
  • Adding a friend
  • Creating a subscription to a channel

Note: Activity feed support for the PHP is only available in Zend_Gdata release 1.7.5 and later.

The following sections explain how to retrieve and process activity feeds:


User activity feeds

To retrieve a user activity feed, make an authenticated request to the following URL. In the request, set the author parameter value to a comma-delimited list of up to 20 YouTube usernames. The API response will contain activities performed by any of those users.

http://gdata.youtube.com/feeds/api/events?author=usernames

The following example sets a list of usernames, retrieves an activity feed for those users, and then prints out some information about each event in the activity feed:

// this example assumes that $yt is a fully authenticated YouTube service object 
$yt
->setMajorProtocolVersion(2); 
 
$activityFeed
= $yt->getActivityForUser("username1,username2,username3"); 
printActivityFeed
($activityFeed); 
 
/** 
 * Print out an activity feed 
 * 
 * @param $activityFeed A Zend_Gdata_YouTube_ActivityFeed 
 * @return void 
 */
 
function printActivityFeed($activityFeed) { 
 
foreach($activityFeed as $activityEntry) { 
    $author
= $activityEntry->getAuthorName(); 
    $activityType
= $activityEntry->getActivityType(); 
   
switch ($activityType) { 
     
case 'video_rated': 
        echo
"$author rated video " . $activityEntry->getVideoId()->text . ' ' . 
          $activityEntry
->getRatingValue() . " stars\n"; 
       
break; 
     
case 'video_shared': 
        echo
"$author shared video " . $activityEntry->getVideoId()->text . "\n"; 
       
break; 
     
case 'video_favorited': 
        echo
"$author favorited video " . $activityEntry->getVideoId()->text . "\n"; 
       
break; 
     
case 'video_commented': 
        echo
"$author commented on video " . $activityEntry->getVideoId()->text . "\n"; 
       
break; 
     
case 'video_uploaded': 
        echo
"$author uploaded video " . $activityEntry->getVideoId()->text . "\n"; 
       
break; 
     
case 'friend_added': 
        echo
"$author friended " . $activityEntry->getUsername()->text . "\n"; 
       
break; 
     
case 'user_subscription_added': 
        echo
"$author subscribed to channel of " .  
          $activityEntry
->getUsername()->text . "\n"; 
       
break; 
   
} 
 
} 
}

Friend activity feeds

To retrieve a friend activity feed, make an authenticated request to the following URL. Note that a user can only retrieve the friend activity feed for her own friends.

http://gdata.youtube.com/feeds/api/users/default/friendsactivity

The following example retrieves the logged-in user's friend activity feed and then prints information about each event in the feed:

// this example assumes that $yt is a fully authenticated YouTube service object 
$yt
->setMajorProtocolVersion(2); 
 
$friendActivityFeed
= $yt->getFriendActivityForCurrentUser(); 
printActivityFeed($friendActivityFeed);

Conclusion

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

And

And

###################################################################

1번째 방법

###################################################################

<html>
<body>
<script event="EndOfStream" for="MMPlayer" language="javascript">
 alert("동영상 끝나면 실행되는 스크립트");
</script>
<embed type="application/x-mplayer2"
pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/Me
diaPlayer/" name=MMPlayer showcontrols=1 autostart=1 autosize=1
filename="http://www.cast21.co.kr/media/master.WMV" showdisplay=0
showstatusbar=0 displaysize=0 width=95% height=97% showcaptioning=0></embed>
</body>
</html>

###################################################################

2번째 방법

###################################################################

#. 안녕하세요 : ) .#

#. playState 속성을 사용하실 수 있습니다.
    다음 url을 참고하세요 :

http://msdn.microsoft.com/library/default.asp?url=/workshop/author/behaviors/reference/properties/playstate.asp

    <object width="320" height="236"
classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" id="MPlay1"
name="MPlay1" VIEWASTEXT>
    ..라는 object 태그를 썼다면,

MPlay1.onPlayStateChange = stateconfirm(MPlay1)
function stateconfirm(player)
{
    if(player.playState == 8 ) ' The player has reached the end of the
media.
    {
        // 플레이가 완료된 것을 확인하는 코드를 삽입
    }
}
And
And

meta element는 현재 페이지를 정의하거나 관련한 모든 사항을 담고 있으며 이러한 사실을 http client에게 알립니다.

developer간의 약속에 따라 meta는 적어도 반드시 body의 시작점 위에, head container안에 존재하여야 합니다.

 

 

meta Element의 종루에는 어떠한 것이 있습니까?




1. meta http-equiv="content-type" content="text/html;charset=euc-kr"

 현재 페이지가 한글로 입력되었고 한글로 인코딩 할 것임을 의미함.

2. meta http-equiv="refresh" content="t;url:url"

 t초 후에 특정 url로 이동하게 함.

3. meta name="keyword" content="a,b,c,d,e"

 meta Keyword Search Engine에 한하여 검색에 당하기 위해 자신의 웹페이지에 a,b,c,d,e 키워드를 설정한다.

4. meta name="description" content="text"

 해당 페이지의 설명(text)을 입력한다.

5. meta name="author" content="author"

 현재 페이지의 제작자 이름 및 단체 이름(author)을 입력한다.

6. meta http-equiv="Content-Script-Type" content="text/javascript"

 해당 페이지는 text와 javascript로 제작된 페이지임을 알린다.

7. meta name="generator" content="tech"

 해당 페이지는 어떠한 프로그램 및 기술으로 제작되었는지를 알림.

8. meta http-equiv="Page-Enter" content="RevealTrans (Duration=3, Transition=23)"

 페이지에 엑세스하거나 나갈 때 여러가지 효과로 접근할 수 있게 한다.

9. meta http-equiv="imagetoolbar" content="no"

 이미지에 마우스를 롤-오버하면 나타났던 툴바(다운로드, 프린트..)가 사라지게 한다.

10. meta name="classification" content="text"

 어떤 형식의 웹페이지인지를 분류한다.
And

 

웹브라우저에 동영상이 보여질지라도 각종 기술이 사용되어 실제 주소를 찾는 것은 매우 힘들다. URL Snooper는 바로 이러한 어려움을 간단히 해결해 주는 프로그램이다. 그러나 무료로 사용할 수 있는 반면 라이센스 키를 등록해야 하는 불편이 있다. (※ 글 수정 정보 : 2007년 8월 15일에 핵심 내용 수정 완료, 2008년 12월 26일에 일부 보완.)

 



≫ 알림 : 이 글은 2007년에 작성한 오래된 글입니다. 일부 내용은 2008년 현시점에서 맞지 않은 부분이 있습니다. 그래서 2008년에 새로 작성하였으므로, 아래 링크를 클릭하여 참조하시기 바랍니다. 다만 본 게시물 자체도 일부 내용은 여전히 참조할 만한 가치가 있고 일부 적용 가능한 부분도 있습니다.



 

 URL Snooper 설치 및 최적화 하는 방법

 

1. 프로그램 다운로드는 제작사인 DonationCoder.com 사이트를 방문하면 된다. 글을 쓰는 현시점에서는 버전 v2.18.01 Beta(Feb 7th, 2007)가 최신이며 윈도우 비스타를 지원하고 있다. 다만 베타 버전은 문제가 발생할 수 있으므로 유의해야 한다. 그리고 프로그램을 설치할 때에는 가급적 다른 프로그램은 종료한 후에 설치를 할 것이 권장된다.


http://www.donationcoder.com/Software/Mouser/urlsnooper/index.html

 


 

2. URL Snooper를 사용하기 위해서는 추가적으로 WinPCap 프로그램도 반드시 필요하다. URL Snooper를 처음 설치하는 경우에는 자동으로 설치를 할 수 있다. 물론 이미 사용하고 있다면 WinPCap의 추가 설치는 필요없다. WinPCap 관련 상세 사항은 제작사 사이트에서 확인할 수 있으며 윈도우 비스타를 지원한다.

 

 

 

3. URL Snooper 설치 후에 프로그램을 실행하면, 프로그램에 대한 소개와 등록, 그리고 자동으로 네트워크 어댑터를 감지한다. 본 화면으로 들어가면 간단한 모습을 보여준다. 기본적으로는 멀티미디어의 주소(Multimedia URLs)만 보여준다.

(※ 네트워크 자동 감지에 실패할 경우, “General Options 탭에서 Auto determine Network Adapter Startup”의 체크를 해제하도록 하고, Network Adapter에서 자신에게 맞는 네트워크 어댑터를 선택하도록 한다. 그리고 Search 탭에서 Sniff Network를 직접 시작하여 주소를 추출할 수 있도록 준비하면 된다.)

 


 

4. 메뉴 “File  Advanced Mode”를 선택하면 전체 주소를 파악할 수 있는데, 이는 유튜브와 같이 멀티미디어 주소로만 파악할 수 없는 경우에 유용하다. 사용 방법은 Protocol Filter에서 전체보기(Show All)를 하면 된다. 그러나 추출되는 주소가 복잡하므로, 잘 찾아내는 안목이 필요하다.

 

 


 

5. URL Snooper는 무료로 사용할 수 있지만 등록하지 않을 경우 10일 정도만 사용할 수 있다. 확인 방법은 Help 메뉴의 About에서 가능하다. 그러나 라이센스 키를 등록하면 6개월(SIGNUP) 또는 60일(NON-SIGNUP) 동안 무료로 사용할 수 있다. 


http://www.donationcoder.com/Keys/

http://www.donationcoder.com/Keys/nosignup.php

 


 


 URL Snooper 프로그램 사용 방법

 

1. URL Snooper를 실행한 상태에서 웹사이트를 방문해 보면 멀티미디어 주소 목록이 나타나는 것을 확인할 수 있다. 하지만 여러 주소 중에서 자신이 원하는 동영상의 주소를 찾는 것은 약간의 눈썰미가 필요하다. 좀 더 쉽게 찾기 위해서는 URL Snooper의 화면에서 Clear Results(결과 삭제)를 누르거나, 또는 빈 공간에서 마우스 오른쪽 버튼을 클릭하여 Clear All URLs Shown(봤던 목록 삭제)를 선택한 후 동영상이 들어있는 주소로 바로 접속하거나 혹은 새로고침(Refresh) 하면 좀 쉽게 찾을 수 있을 것이다. 

그렇다면, 예를 들어 보자. 아래 예제에서는 네이버 뉴스에 접속한 화면이다. 해당 화면 접속 후 URL Snooper 프로그램을 실행한다. 그리고 웹브라우저에서 “동영상 보기”를 클릭한다. 그러면 동영상이 들어있는 주소가 나타날 것이다. 물론 다른 동영상의 경우에는 해당 화면에서 바로 웹브라우저를 새로고침(Refresh) 해도 되는 경우도 있다. 그런데 일부 동영상 서비스 업체의 경우 재생(play ; ▶) 버튼을 눌러야 실제 주소가 추출되는 경우도 있다.

 


 

2. URL Snooper에서 동영상 주소를 찾았다면 마우스 오른쪽 버튼을 클릭하여 복사를 한 후, 넷트랜스포트(Net Transport)에서 바로 다운로드 하면 된다. 동영상 주소 확인은 스트리밍 파일이 mms://로 시작한다는 것에서 착안하면 된다. 물론 mms:// 형식을 취하고 있더라도 실제 프로토콜은 rtsp://인 경우도 있다. 주소가 동일하다면 mms:// 또는 rtsp:// 주소 모두 상관없다. 다만 네이버 블로그의 동영상은 rtsp 주소만 유효한 것으로 추정된다.



≪ 활용 팁 ≫ 

⒜ 다음 TV팟이나 엠엔캐스트 등과 같은 동영상의 경우(즉 스트리밍이 아니라 일반적으로 쉽게 다운 받을 수 있는 동영상일 경우) URL Snooper에서 주소를 추출할 경우, 화면 오른쪽 부분의 Protocol 부분에 "Get..."과 같이 나온다면(혹은 나오지 않는다하더라도) 더블 클릭하여 바로 다운 받는 것도 가능하다.

⒝ URL Snooper를 나중에 다시 실행하였을 경우, 동영상이 추출되지 않는 경우가 있다. 이때에는 URL Snooper의 "Sniff Network" 또는 "Open in Browser"를 클릭하여 주소를 추출할 수 있도록 하면 된다.

 

 

 

 

 


 

3. URL Snooper를 이용하면 네이버 뉴스뿐만 아니라 KBS, MBC, SBS, YTN 등의 뉴스 동영상 주소를 찾을 수 있으며 넷트랜스포트로 다운로드 할 수 있다.경험상 MBC 뉴스 동영상의 경우에는 뉴스 전체 분량의 동영상이 다운된다. 이는 전체 뉴스 동영상 중에서 일부분만 보여주도록 하는 특성 때문인데, 다른 곳에서 사용하고자 할 경우 분할을 해야 하는 등 어려움이 예상된다.

어쨌든 해당 동영상들은 대부분 wmv, asf 파일 포맷을 사용하고 있으므로 파워 포인트와 같은 곳에 삽입할 경우 문제없이 삽입 및 재생이 가능하다. 유의할 점은 동영상의 경로인데, 해당 문서와 동일 폴더 내에 동영상 파일을 넣고 링크한다면 문제 없을 것이다.

 

 

 

 URL Snooper 사용시 참고 사항

 

1. 다음의 TV팟은 찾기가 수월하다. 동영상이 있는 화면에 접속만 해도 주소를 확인할 수 있다. 특히 플래쉬 비디오(FLV) 파일이라는 점에 착안하면 쉽게 찾을 수 있다. 대부분의 유사 서비스는 이와 동일하다. 다운로드는 넷트랜스포트와 같은 프로그램을 이용해도 되지만 소용량일 경우에는 “해당 주소를 더블 클릭함으로써 바로 다운” 받아도 될 것이다.

 

 

※ 참고 : 엠엔캐스트의 동영상의 경우에는, 동영상의 재생 화면에서 바로 주소가 추출되지 않을 수도 있다. 이때에는 재생(▶) 버튼을 한 번만 클릭하면 바로 주소가 추출된다. 주소 추출만 할 것이라면, 엠엔캐스트에서는 동영상 재생 버튼 클릭 한 번만 한 후에, 바로 URL Snooper에서 확인하면 된다.
 

※ 주의 : 엠군의 동영상은 URL Snooper에서 추출하더라도 재생시마다 계속 변경되므로 더이상 공유는 불가능하다. 아울러 다운로드는 주소 추출후 바로 더블 클릭시 엠군 사이트로 리다이렉트되는 문제가 있다. 이러한 경우에는 다운로드 그래프가 완료된 후에 다운로드를 시도하거나 또는 임시 인터넷 폴더에서 다운로드된 파일을 복사하면 될 것이다.


 

2. 유튜브 동영상은 조금 까다롭다. 멀티미디어의 주소(Multimedia URLs) 옵션에서는 찾을 수 없으므로 전체보기(Show All)를 한 후에, get_video가 있는 부분을 찾으면 된다. 물론 다른 주소도 get_video가 포함된 경우가 있으나, 실제 동영상이 들어있는 주소는 길이가 길다는 점에 착안한다.
그리고 넷트랜스포트에서는 유튜브 동영상과 같은 경우에는 "이름변경" 부분에서 파일 이름과 확장자를 직접 작성해 주는 것이 좋다. 지정하지 않을 경우 파일 이름과 확장자를 추후 다시 지정해 주어야 하는 번거로움이 있기 때문이다.

 

 


 

3. URL Snooper를 이용하면 네이버의 동영상도 다운로드 할 수 있다. 즉 네이버에서 지원하는 동영상 올리기로 업로드한 경우(기존의 네이버 블로그 및 카페에 지원되는 동영상 업로드)에 URL Snooper로 주소를 추출하고 넷트랜스포트에서 다운로드 하면 된다(기존 스트리밍 방식에 대한 설명임, 그러나 2007년 중반 이후부터는 플래쉬 비디오 파일 형식으로 제공됨). 아울러 추출한 동영상 주소는 한 번 만 사용할 수 있으므로, 다시 다운 받기 위해서는 URL Snooper에서 다시 추출해야 한다.

그리고 MMS 프로토콜을 지원하지 않고 플래쉬 비디오(FLV) 파일 포맷으로 제공되는 동영상도 있다(2007년 8월 기준으로 조금씩 적용 후, 2008년 현재에는 대부분 적용). 어쨌든 동영상의 파일 포맷이 다르다하더라도 다운로드 방법은 별로 차이가 없다. 특히 FLV 파일 포맷으로 제공되는 동영상은 아무런 프로그램을 사용하지 않고, 단지 다운로드 그래프가 완료된 것을 확인한 후에 임시 인터넷 폴더에서 해당 파일을 찾아 자신의 원하는 폴더로 복사를 해도 된다.

(※ 주의 : 네이버에 업로드 된 동영상은 제한이 걸려있는 경우에는 넷트랜스포트로도 다운받을 수 없는 경우도 있다. 그리고 아래 예제는 2007년 상반기의 블로그 동영상을 예로 든 것이다. 스트리밍으로 제공되던 것이었다. 현재 플래쉬 비디오 파일 형식으로 변경되었으므로, 아래 예제는 단순 참조용으로만 활용하기 바란다.)

 


 

 

  

참고적으로 다운 받은 동영상은 개인적으로만 감상한다면 법적으로는 전혀 문제가 없을 것이다. 그러나 블로그나 미니홈피 등에 업로드하여 다른 사람들과 공유할 경우 불법임으로 유의해야 할 것이다.

'IT 팁' 카테고리의 다른 글

CSS 예제 사이트 모음  (0) 2011.06.16
meta Element 란 무엇인가? 종류안내  (0) 2011.06.16
preg_match_all to match <img> tags  (0) 2011.06.11
파일서버에 업로드, Network Drive에 저장  (0) 2011.06.11
CSS 예제 사이트 모음  (0) 2011.06.10
And

I know this isn't exactly a php related question but due to the
quality of answers ive seen lately ill give this a shot. (yes yes im
smoothing up the crowd before the question)

I have a weblog system that i am creating, the trouble is that if a
user links to an external image larger than 500pixels in width, it
messes with the whole layout.

I had found some regex code im using atm but its not good at matching
the entire image tag. It seems to ignore properties after the src
declaration and not match tags that have properties before the src
declaration .

preg_match_all("/\< *[img][^\>]*[src] *= *[\"\']{0,1}([^\"\'\ >]*)/i",
$data, $matches);
print_r($matches);

This currently makes two arrays for me, the source location from all
img tags and a large part of the tag itself. But not the entire tag.

What i do is i match the img tag, find the src, get the image
properties, and if the width is more than 500, i shrink it down and
add width="X" and height="Y" properties to the image tag.

How can i match an image tag correctly so it does not cause any issues
with how the user adds the image.
.
And

http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=4052&MAEULNo=518&no=1212&ref=1206

DEXTUpload Pro 3.2.0을 설치하고 계정과 권한 설정에 대한 부분의 이해가 늦어 시간이 걸렸습니다.


메뉴얼에 기술되어 있었지만 이해의 폭이 달라 해결하지 못한 것입니다.


제가 잘 못 이해한 부분은 가상디렉토리를 만들어야 가능할 거라는 부분과 가상디렉토리에 계정과 권한을 설정해야 된다는 부분으로

정보를 잘 못 해석했습니다.


우선 저와 같은 실수를 하실 분을 위해 다시 정리하겠습니다.

[웹서버와 파일서버 업로드/다운로드 설정]

1. 운영체제 : 웹서버,파일서버 모두 Window server 2003(영문), IIS 6.0

2. 업로드 컴포넌트 : DEXTUpload Pro 3.2.0 30일 평가판


설정 방법

 

DEXTUpload Professional 프로그래밍


 

 네트워크 경로에 대한 파일 업로드/다운로드

파일 업로드(다운로드) 작업을 수행하는 웹서버와, 업로드한 파일이 저장되는(다운로드할 파일이 저장되어 있는) 파일 서버를 별개의 컴퓨터로 두고자 할 경우에는, 다음과 같은 네트워크 경로의 액세스를 위한 추가적인 설정이  필요합니다.

다음은 각 서버에서 설정해야 하는 것을 설명한 것입니다.

1. 웹 서버와 파일 서버 공통
1).
익명 액세스를 위한 새로운 인터넷 게스트 계정을 생성하고, 암호도 입력합니다.(두 서버의 계정 및 암호는 동일해야 합니다.)


2)
이 계정에 대해 "암호 변경할 수 없음" "암호 사용 기간 제한 없음"이라는 두 개의 항목에만 체크를 하고, "다음 로그온할 때 반드시 암호 변경", "계정 사용 안함", "계정 잠겨 있음" 항목에 대해서는 체크를 하지 않습니다.

img2.gif


3)
만들어진 계정의 소속 그룹 항목에서 이미 기본적으로 추가되어 있는 "Users"그룹을 제거하고, "Guests"그룹 을 추가합니다.
img4.gif

img5.gif

4)
로컬 보안 정책 설정에서 이 계정이 "로컬 로그온" 권한을 가질 수 있도록 합니다.
img6.gif

img7.gif

img8.gif

2. 웹서버 설정
1)
인터넷 서비스 관리자를 실행하여 해당 웹사이트의 디렉토리 등록정보 창을 엽니다.

  'asp_mysql' 웹사이트의 속성에 설정해야 함. (이부분에 설정하지 않고 가상디렉토리를 생성해 설정해서 동작이 안된 것임.)

img9.gif
2) "
디렉터리 보안" 탭에서 "익명 액세스 및 인증 제어" 항목에 있는 "편집"버튼을 클릭합니다.

img10.gif
3)
여기서 "익명 액세스" 항목에 있는 "편집"버튼을 클릭하여, 익명 사용자 이름과 암호란에 위에서 만든 계정의 이름과 암호를 입력하되, 반드시 "IIS에서 암호를 제어할 수 있음"  항목을 체크하지 않도록 합니다.
img11.gif

3. 파일서버 설정
1)
파일서버의 업로드 폴더의 디렉토리 등록정보 창을 엽니다.
2)
폴더를 공유하고 "공유"탭에서의 사용권한과 "보안"탭에서의 사용권한 모두에 대해 위에서 생성한 계정을 추가합니다.
3)
이 때, "공유"탭에서의 사용권한으로는 "읽기" "변경", "보안"탭에서의 사용권한으로는 "읽기", "쓰기", "수정" 권한을 지정해 주도록 합니다.
img12.gif

1, 2, 3의 절차를 거쳐 웹서버와 파일서버를 설정하고 나면, 물리적 절대경로값을 필요로 하는 프로퍼티나 메쏘드에 다음과 같이 간단히 네트워크 경로를 지정함으로써, 파일을 업로드하거나 다운로드할 수 있습니다.
 

1) uploadform.DefaultPath = "\\파일서버명\공유폴더명"
2) uploadform("file1").SaveAs("\\파일서버명\공유폴더명\Sample.zip")
3) oDownload.Download("\\파일서버명\공유폴더명\Sample.zip")

And
And