My favorites | 中文(简体) | Sign in

开发人员指南:PHP

客户端应用程序可以通过 YouTube Data API 以 Google Data API 供稿的形式检索和更新 YouTube 内容。您的客户端应用程序可以使用 YouTube Data API 供稿来获取、搜索和更新视频、评论、响应、播放列表、用户个人资料和用户联系人,以及查询符合特定条件的视频。

除了提供有关 YouTube Data API 功能的部分背景资料外,本文档还提供了使用 PHP 客户端库与 API 进行交互的实例。您可以将客户端库作为单机版(由 Zend 分发)或 Zend Framework 的一部分进行下载。如果您在设置 PHP 客户端库时需要帮助,可以查看《使用入门指南》。如果您对 PHP 客户端库与 YouTube 交互时所使用基本协议的详情感兴趣,请查看开发人员指南的协议网页

目录

关于本文档

读者

本文档适用于想要编写可以使用 PHP 客户端库与 YouTube 进行交互的客户端应用程序的编程人员。本文档提供了基本数据 API 交互的一系列实例。

有关 YouTube Data API 参考信息,请参阅参考指南

本文档假设您已大体了解 Google Data API 协议,并已了解 PHP。

有关 PHP 类和方法的参考信息,请参阅客户端库的 API 指南

文档结构

本文档包含以下小节:

  • “验证”一节介绍了可用来将 API 操作与特定用户账户关联的两种不同验证方法。该小节还概述了 YouTube Data API 验证与其他 Google Data API 验证之间的差异。整篇文档中,对特定 API 功能的说明将明确指出该功能是否需要用户验证。通常所有修改视频或供稿数据的请求均需要验证。对公开视频的只读请求无需验证。

  • “了解视频供稿和条目”一节提供了一个示例 API 响应,并说明了从视频列表或一组搜索结果中提取单个视频信息的方式。该小节还说明了访问特定视频条目的元数据的方式。最后,该小节说明了更新单个视频条目的机制。

  • “检索和搜索视频”一节说明了获取特定视频列表的方式。这些列表中有多种类型的标准供稿(例如“评分最高的视频”或“查看次数最多的视频”)。其他视频列表包含由特定用户上传的视频和与特定视频相关的视频列表。该小节还说明了用户如何使用 API 按特定搜索项或类别在 YouTube 视频库中进行搜索。

  • “上传视频”一节简要说明了您允许用户从您的应用程序向 YouTube 上传视频的两种方式。此外,该小节还说明了上传视频作为对其他视频之响应的方式。

  • “更新与删除视频”一节介绍了使用 API 更新有关 YouTube 视频的信息的方式。该小节还介绍了使用 API 删除视频的方式。

  • “使用社区功能”一节介绍了您的用户可以用来与 YouTube 视频交互的 API 功能。这些功能说明了对现有视频发布评分、评论、视频响应或投诉的请求。您还可以使用 API 来检索视频评论列表或视频响应或删除视频响应。

  • “保存与收集视频”一节说明了使用 API 访问、创建和更新最爱的视频、视频播放列表及对 YouTube 频道的订阅的方式。该小节还显示了通过添加与删除视频来修改视频播放列表和喜欢的视频的方式。

  • “启用用户交互”一节说明了使用 API 检索和更新用户个人资料的方式。该小节还说明了检索、添加、更新和删除用户联系人的方式,以及检索、发送和删除讯息的方式。

使用入门

要求

要使用 PHP 客户端库,您必须运行 5.1.4 或更高版本的 PHP。您还需要使用 1.5RC2 或更高版本的 Zend_Gdata(作为 Zend Framework 的一部分分发)。请参阅《使用入门指南》以获得有关配置您的环境的详细信息。

以下示例代码的片段可以复制/粘贴到您的代码并进行修改,以满足您的需要。此外,还有与包含许多 API 操作的客户端库一起分发的示例应用程序。代码位于 http://framework.zend.com/svn/framework/demos/Zend/Gdata/YouTubeVideoApp

使用 YouTube Data API 执行任何操作之前,您必须初始化一个 Zend_Gdata_YouTube 对象,如下所示。请注意,除检索公开内容之外的所有操作都要求验证

<?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();

对于已验证的功能,您还需要在确定是否打算使用 ClientLogin 或 AuthSub 之前,包含以下辅助类之一(有关详细信息,请参阅以下“验证”一节)。

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

本指南中的大部分方法实例均在以下示例上运行: Zend_Gdata_YouTube

注意:Zend library 目录的内容必须位于 PHP include_path 中。

验证

PHP 客户端库既可用于公开供稿,也可用于私人供稿。公开供稿是只读的,无需任何验证。私人供稿需要您向 YouTube 服务器进行验证。此外,您需要注册以获得 YouTube 开发人员密钥。验证可以通过 ClientLogin 进行,该验证方式会使用用户名/密码执行验证,或通过 AuthSub 执行代理验证。

网络应用程序的 AuthSub 验证

AuthSub 代理验证由网络应用程序使用,而网络应用程序需要向 YouTube/Google 帐户验证其用户。操作者无需访问 YouTube 用户的用户名和密码,只需要特殊的 AuthSub 令牌即可。

用户初次访问您的应用程序时,Google 的服务尚未对其进行验证。在这种情况下,您需要为其提供一个链接,该链接会引导用户到 Google 以验证您访问其 YouTube 帐户的请求。Zend Framework PHP Google Data 客户端库提供了生成该网址的功能。以下代码可以建立到 AuthSubRequest 网页的链接。

// start a new session 
session_start();

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

上述代码生成的网址需要来自 Google 的 YouTube 服务的令牌。请注意发送到 getAuthSubRequestUrl 方法的参数:

  • $next — 验证后 Google 应将 用户重新引导到的网页的网址。
  • $scope — 表示应用程序可以访问的供稿的范围。
  • $secure — 表示返回的令牌将被撤消注册。
  • $session — 表示以后可以将该令牌交换 为多用途(会话)令牌。

以下是网址示例:

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

然后用户可以跟踪该链接到 Google 的网站,并验证其 Google 帐户。用户返回您应用程序的$next网址后,会发送一次性令牌并重新引导至:http://mysite.com/welcome.php?token=DQAADKEDE

为保证安全,该令牌只能使用一次,因此我们现在需要将该一次性使用的令牌交换为会话令牌。以下代码片段显示了升级令牌的方式。

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

在该片段中,$_GET['token'] 变量包含来自网址中 token 查询参数中的值。该令牌值代表一个一次性使用的 AuthSub 令牌。由于我们在上述 getAuthSubRequestUrl 函数中指定 $session = true,因此可以将该令牌交换为 AuthSub 会话令牌(与上述调用 getAuthSubSessionToken 时代码完成的操作相同)。

以下函数可以执行所有此类请求。首先检查是否已设置了会话令牌。如果未设置,则会使用之前介绍的 getAuthSubRequestUrl 函数创建验证网址。如果在网址字符串 ($_GET['token']) 中找到一次性使用的令牌,则会将其升级为会话令牌。最后,会使用您的开发人员密钥创建并返回经过完全验证的 Zend_Gdata_Http_Client 对象。

function getAuthSubHttpClient($developerKey)
{
    if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
        echo '<a href="' . getAuthSubUrl() . '">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']);
    $httpClient->setHeaders('X-GData-Key', "key=${developerKey}");
    return $httpClient;
}

然后您可以创建经过完全验证的 YouTube 服务对象,创建方式是将您的 $httpClient 传到 Zend_Gdata_YouTube 服务对象的构建程序:

$yt = new Zend_Gdata_YouTube($httpClient);

然后可以使用 YouTube API 对该完全验证的服务对象执行所有进一步的请求。只有在您专门提出撤销 AuthSub 会话令牌的请求,或用户决定通过访问授权的站点网页来撤销访问时,AuthSub 会话令牌才会过期。

已安装应用程序的 ClientLogin 验证

ClientLogin 验证用于可以储存或查询您用户的用户名和密码的已安装的应用程序。要使用该形式的验证,请调用 Zend_Gdata_ClientLogin 类的静态 getHttpClient 方法,指定您的应用程序代表其发送查询之用户的电子邮件和密码。请注意,您还必须传达以下指定的网址进行验证。例如:

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

设置证书后,$httpClient 对象可以用于验证所有对 Zend_Gdata_YouTube 服务对象的进一步请求。请确保也将开发人员密钥传到 $httpClient

$myDeveloperKey = 'ABC123 ... ';
$httpClient->setHeaders('X-GData-Key', "key=${myDeveloperKey}");
$yt = new Zend_Gdata_YouTube($httpClient);

有关 AuthSub 和 ClientLogin 机制的详细信息,请参考 Google Data API 验证文档

了解视频供稿和条目

YouTube Data API 提供代表视频列表的数种视频供稿,例如标准供稿、上传、订阅和喜欢的视频。每个供稿的网址均记录在参考指南中。

显示视频的供稿

YouTube API 中的许多供稿由视频条目组成。这些供稿可以简单地比拟为 Zend_Gdata_YouTube_VideoFeed 对象,每个对象包含许多 Zend_Gdata_YouTube_VideoEntry 对象。每个视频条目都与 YouTube 上的一部视频精确对应,并且包含视频的信息。

检索视频列表的基本结构是构建到视频供稿的网址,然后一次处理一个条目,与以下代码类似:

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
  }
}

“检索和搜索视频”一节详细介绍了许多常见的供稿网址及检索各种视频供稿的方式。

检索特定视频条目

如果知道特定视频条目的视频 ID,您可以只检索信息。条目网址是基于视频 ID 的:

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

以下代码可以检索与 YouTube 上的视频对应的 VideoEntry

$yt->getVideoEntry('the0KZLEacs');

视频条目内容

有许多可以从 VideoEntry 对象中检索出的元数据片段,例如缩略图、播放器网址和视频时长。以下代码演示了获得某些此类信息的方式。PHP 客户端库通过将 XML 元素映射到 PHP 类中概括了此功能的大部分。有关 VideoEntry 条目的大部分重要信息可在 media:group 元素的子元素中找到,而该元素来源于 VideoEntry。该 XML 元素被映射到 MediaGroup 对象,可以通过调用 $videoEntry->getMediaGroup()$videoEntry->mediaGroup 对其进行检索。我们已向客户端库添加了许多辅助方法,不仅有助于轻松访问 mediaGroup 的子元素,还可以从 VideoEntry 对象中直接调用。该方法的一个实例为:$videoEntry->getVideoTitle()

function printVideoEntry($videoEntry, $tabs = "") 
{
  // the videoEntry object contains many helper functions that access the underlying mediaGroup object
  echo $tabs . 'Video: ' . $videoEntry->getVideoTitle() . "\n";
  echo $tabs . "\tDescription: " . $videoEntry->getVideoDescription() . "\n";
  echo $tabs . "\tCategory: " . $videoEntry->getVideoCategory() . "\n";
  echo $tabs . "\tTags: " . implode(", ", $videoEntry->getVideoTags()) . "\n";
  echo $tabs . "\tWatch page: " . $videoEntry->getVideoWatchPageUrl() . "\n";
  echo $tabs . "\tFlash Player Url: " . $videoEntry->getFlashPlayerUrl() . "\n";
  echo $tabs . "\tDuration: " . $videoEntry->getVideoDuration() . "\n";
  echo $tabs . "\tView count: " . $videoEntry->getVideoViewCount() . "\n";
  echo $tabs . "\tRating: " . $videoEntry->getVideoRatingInfo() . "\n";
  echo $tabs . "\tGeo 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 $tabs . "\tMobile RTSP link: " . $content->url . "\n";
    }
  }
  
  echo $tabs . "\tThumbnails:\n";
  $videoThumbnails = $videoEntry->getVideoThumbnails();

  foreach($videoThumbnails as $videoThumbnail) {
    echo $tabs . "\t\t" . $videoThumbnail->time . " - " . $videoThumbnail->url;
    echo " height=" . $videoThumbnail->height;
    echo " width=" . $videoThumbnail->width;
    echo "\n";
  }
}

对于在网页中使用播放器嵌入的视频,有关生成视频所需信息之方式的详细信息,请参考协议指南。

检索和搜索视频

检索标准供稿

YouTube Data API 目前可以提供符合多种条件视频的标准供稿。这些供稿是站点范围内的,不是针对用户的。所有标准供稿的网址的开头都是 http://gdata.youtube.com/feeds/api/standardfeeds/, 之后是供稿的标识符。下表列出了可用的供稿:

供稿名称供稿标识符
查看次数最多most_viewed
评分最高top_rated
最新精选recently_featured
用手机观看watch_on_mobile
讨论最多most_discussed
收藏最多top_favorites
链接最多most_linked
响应最多most_responded
最新most_recent

您也可以通过指定 http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID 格式的 localeID 来检索位置特定的标准供稿。例如,在日本查看次数最多的视频可能是:http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_viewed。要获得可能的 localeID 的完整列表,请参考参考指南。

以下实例显示了使用 YouTube::getVideoFeed()方法获取并打印这些标准供稿的方式。

这些供稿中部分的网址可以定义为常量,部分网址也可以通过辅助方法检索,但您也可以使用参考指南中定义的值来手动构建网址。请注意,检索标准供稿时无需验证您的 Zend_Gdata_YouTube 服务对象。

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

VideoFeed 对象是 VideoEntry 对象的集合。以下辅助函数可以打印供稿中返回视频的详细信息:

function printVideoFeed($videoFeed, $displayTitle = null) 
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $videoFeed->title->text;
  }
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
  foreach ($videoFeed as $videoEntry) {
    echo 'Entry # ' . $count . "\n";
    printVideoEntry($videoEntry);
    echo "\n";
    $count++;
  }
  echo "</pre>\n";
}

检索由特定用户上传的视频

每个 YouTube 用户都有一个与其上传的视频对应的相关视频供稿:http://gdata.youtube.com/feeds/api/users/username/uploads。以下代码演示了获取并显示用户上传内容之供稿的方式:

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

您还可以使用字符串“default”代替 $userName 来检索目前已验证用户的视频。

检索相关视频

要检索相关视频,请将 Video_Entry 对象的视频 ID 传到 Zend_Gdata_YouTube 对象的 getRelatedVideoFeed 方法。这样可以检索包含相关条目的 VideoFeed 对象。

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

搜索视频

您可以使用 YouTube Data API 请求一组符合指定条件的条目,例如请求由特定作者发布的视频条目、以视频格式发布的视频条目或包含特定关键字的视频条目。要实现此操作,请使用特定搜索条件创建 VideoQuery 对象,然后将其传到 YouTube::getVideoFeed() 方法。

例如,要执行关键字查询并按观看次数排序结果,其中包括受限的视频(API 称之为“猥亵内容”),请使用 VideoQuery 对象的 setVideoQuerysetOrderBysetRacy 方法。以下代码片段可以打印符合指定关键字的所有视频的标题和摘要,按查看次数排序并包括受限的视频:

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

可以使用Query 类和子类(如 VideoQuery)构建供稿网址。上述 VideoQuery 可构建与以下内容相同的网址:

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

以下是设置搜索参数的一些最常用的 VideoQuery 方法:

setAuthor
设置条目的作者。作者与 YouTube 用户名同义。
setFormat
指定视频格式。可接受为移动视频播放指定两种 RTSP 流网址之一的数字参数,或为嵌入式 Flash 播放器指定 HTTP 网址的数字参数。
setRacy
表明结果中是否应包含受限的内容。只接受两个参数:“include”或“exclude”。
setMaxResults
设置一次返回条目的数量上限。
setStartIndex
设置要检索的第一个结果的索引(从 1 开始,用于分页)。
setOrderBy
设置列出条目的顺序,例如按 RELEVANCEVIEW_COUNTUPDATEDRATING 列出。
setTime
设置时间期限,将标准供稿结果限制为:TODAYTHIS_WEEKTHIS_MONTHALL_TIME
setVideoQuery
设置搜索查询项目。搜索所有视频元数据中的指定字符串,例如标题、标签和说明。

如果您想设置在 VideoQuery 类中没有相应辅助方法的参数,可以通过调用 $query->setParam('name', 'value') 方法来设置自定义参数。有关查询参数的详细信息,请参阅《YouTube Data API 参考指南》和《Google Data API 参考指南》。

使用类别和关键字搜索

您可以将搜索结果限制为仅显示符合指定的一组类别和关键字的视频。参考指南介绍了指定预定义的 YouTube 类别和用户定义的关键字(称为标签)的方式。

以下代码演示了通过将搜索项更改为小写字母来使用关键字(标签)搜索的方式。请注意:由于某些字词(例如“comedy”)既可以是 YouTube 类别也可以是关键字,因此类别和关键字查询的惯例是使用大写字 (“Comedy”) 表示 YouTube 类别,用小写字 (“comedy”) 则表示关键字。

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:');
}

按开发人员标签搜索

开发人员标签是开发人员可能用于标记其上传内容的附加的、隐藏的关键字。这些关键字不会公开显示,但是可以用于检索视频。要按特定开发人员标签搜索视频,请发送一般 YouTube Data API 搜索请求,并确保指定视频必须匹配的类别方案和开发人员标签。要通过开发人员标签访问视频,不需要验证客户端,但是必须在标题中设置您的开发人员密钥。您可以从以下网址中检索与您的开发人员标签(实例中为“your_tag_here”)匹配的视频的供稿:

$devTagUrl = "http://gdata.youtube.com/feeds/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);

上传视频

请确保查看协议指南中的图表,以更好地了解上传过程的概述。上传视频有两种方式:直接上传视频,或者只发送视频元数据然后让用户通过 HTML 形式上传视频。

直接上传

要了解更多 developers_guide_protocol.html#Process_Flows_for_Uploading_Videos 要上传视频,您必须先构建一个新 VideoEntry 对象,并指定部分所需成员。以下实例显示了向 YouTube 上传具以下属性的 Quicktime 视频“mytestmovie.mov”的过程:

属性
标题我的测试影片
类别汽车
关键字车,有趣
说明我的说明
文件名mytestmovie.mov
文件 MIME 类型视频/quicktime
是否为私人视频?虚假
视频位置37,-122(纬度,经度)
开发人员标签mydevelopertag,anotherdevelopertag

以下代码可以创建要上传的空白 VideoEntryZend_Gdata_App_MediaFileSource 对象用来保留实际的视频文件。Zend_Gdata_YouTube_MediaGroup 对象则用来保留视频元数据。$uploadUrl 是要发布新条目的位置。这个可以使用目前已验证用户的 $userName 来指定,您还可以只使用字符串“default”来表示目前已验证用户。

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

// create a new Zend_Gdata_YouTube_MediaGroup object
$mediaGroup = $yt->newMediaGroup();
$mediaGroup->title = $yt->newMediaTitle()->setText('My Test Movie');
$mediaGroup->description = $yt->newMediaDescription()->setText('My description');

// the category must be a valid YouTube category
// optionally set some developer tags (see Searching by Developer Tags for more details)
$mediaGroup->category = array(  
  $yt->newMediaCategory()->setText('Autos')->setScheme('http://gdata.youtube.com/schemas/2007/categories.cat'), 
  $yt->newMediaCategory()->setText('mydevelopertag')->setScheme('http://gdata.youtube.com/schemas/2007/developertags.cat'),
  $yt->newMediaCategory()->setText('anotherdevelopertag')->setScheme('http://gdata.youtube.com/schemas/2007/developertags.cat')
  );

// set keywords
$mediaGroup->keywords = $service->newMediaKeywords()->setText('cars, funny');
$myVideoEntry->mediaGroup = $mediaGroup;

// set video 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);
$entry->setWhere($where);


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

try {
  $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_Exception $e) {
    echo $e->getMessage();
}

基于浏览器上传

除了不将 MediaFileSource 对象附加到正在构建的 VideoEntry 之外,基于浏览器上传的执行过程与直接上传几乎相同。您只需提交视频的所有元数据,以便接收可用于构建 HTML 上传形式的令牌元素。

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

// set up media group as in the example above
$mediaGroup = $yt->newMediaGroup();
$mediaGroup->title = $yt->newMediaTitle()->setText('My Test Movie');
$mediaGroup->description = $yt->newMediaDescription()->setText('My description');

// note the different schemes for categories and developer tags
$categoryScheme = 'http://gdata.youtube.com/schemas/2007/categories.cat';
$developerTagScheme = 'http://gdata.youtube.com/schemas/2007/developertags.cat';

$mediaGroup->category = array(  
    $yt->newMediaCategory()->setText('Autos')->setScheme($categoryScheme),
    $yt->newMediaCategory()->setText('mydevelopertag')->setScheme($developerTagScheme),
    $yt->newMediaCategory()->setText('anotherdevelopertag')->setScheme($developerTagScheme)
    );

$mediaGroup->keywords = $yt->newMediaKeywords()->setText('cars, funny');
$myVideoEntry->mediaGroup = $mediaGroup;

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

以上代码可以打印一个链接和一个用于构建 HTML 形式的令牌,以显示用户的浏览器。下面显示了一个简单的实例,$tokenValue 代表返回的令牌元素的内容,如上所示从 $myVideoEntry 中检索的内容。为了在用户提交形式后将其重新引导到您的网站,请确保将 $nextUrl 参数附加到上述 $postUrl(其功能与 AuthSub 链接中的 $next 参数相同)。唯一的差异在于,在网址中会返回状态id 变量,而不是返回一次性使用的令牌。

// place to redirect user after upload
$nextUrl = 'http://mysite.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://mysite.com/youtube_uploads
http://mysite.com/youtube_uploads?status=200&id=JPF-DXF7hzc

status 参数可以返回上传事务的 HTTP 事务状态。id 参数可以返回分配给已上传视频的 YouTube 视频 ID。

检查上传状态

上传视频后,将会立即显示在已验证用户的上传内容供稿中。但是,视频只有经过处理后才能在网站上公开。被拒绝或无法成功上传的视频也只会显示在已验证用户的上传内容供稿中。以下代码可以检查 VideoEntry 的状态,以确定其是否尚无法观看或是否已遭拒绝。

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

更新与删除视频

更新视频信息

要更新视频元数据,只需更新 VideoEntry 对象然后使用 Zend_Gdata_YouTube 服务的 updateEntry 方法。请注意,由于 updateEntry 发布了 http PUT 请求,您必须使用视频条目的“编辑”链接作为位置。以下代码演示了更新视频的标题的方式,以及获得要向其发送更新的视频之“编辑”链接的方式。

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

删除视频

删除视频很简单,只需检索已验证用户的上传供稿,调用 Zend_Gdata_YouTube 服务对象上的 delete() 方法,然后传入要删除的 VideoEntry即可。

$yt->delete($videoEntryToDelete);

使用社区功能

添加评分

要对视频评分,只需向 VideoEntry 添加一个评分对象,并将其发布到该 VideoEntry 的评分链接。

// create a new Zend_Gdata_App_Entry
$ratingEntry = $service->newEntry();

// create a new Zend_Gdata_App_Extension_Rating element
$rating = $service->newRating();
$rating->setMax(5);
$rating->setMin(1);

// create a custom attribute for gd:rating value="5",
// setting the new rating to be submitted to '5 stars'
$rating->setExtensionAttributes(array(array('namespaceUri' => 'http://schemas.google.com/g/2005', 'name' => 'value', 'value' => '5')));

// add the extension element to the rating entry
$ratingEntry->extensionElements = array($rating);

// obtain the ratings url for the video that you wish to rate  
$ratingUrl = $videoEntry->getLink('http://gdata.youtube.com/schemas/2007#video.ratings')->getHref();

// post the $ratingEntry to the $ratingUrl using the insertEntry method of the Zend_Gdata_YouTube service object
try {
  $response = $service->insertEntry( $ratingEntry, $ratingUrl );
} catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
}

评论

检索视频的评论

指定 VideoEntry 对象,您可以使用以下代码检索并打印包含视频的评论的供稿:

getAndPrintCommentFeed($videoEntry->videoId);

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

function printCommentFeed($commentFeed, $displayTitle = null) 
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $commentFeed->title->text;
  }
 
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
 
  foreach ($commentFeed as $commentEntry) {
    echo 'Entry # ' . $count . "\n";
    printCommentEntry($commentEntry);
    echo "\n";
    $count++;
  }
  echo "</pre>\n";
}

function printCommentEntry($commentEntry) 
{
  echo 'Comment: ' . $commentEntry->title->text . "\n";
  echo "\tFull text: " . $commentEntry->content->text . "\n";
  echo "\tAuthor: " . $commentEntry->author->name->text . "\n";
}

添加评论

要添加新评论,只需使用 Zend_Gdata_YouTube 服务对象。

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

// post the comment to the comment post URL
$comment_post_url = 'http://gdata.youtube.com/feeds/videos/'. $video_id .'/comments';
$updatedVideoEntry = $yt->insertEntry( $comment2, $comment_post_url );

删除评论

要删除评论,您必须先通过 Zend_Gdata_YouTube_CommentFeed 对象检索评论。之后,您便可以使用 Zend_Gdata_YouTube 服务对象删除特定 CommentEntry

$yt->delete($commentEntryToBeDeleted);

视频响应

检索视频的视频响应

视频供稿中的每个视频条目都有一个相关的视频响应供稿,其本身也是视频供稿。此代码演示了对于指定的 VideoEntry,检索并打印其视频响应之信息的方式:

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

在该实例中,我们重新使用 getAndPrintVideoFeed() 函数。在这种情况下,供稿网址不是手动构建的,而是通过调用 VideoEntry::getVideoResponsesLink()->getHref() 动态检索的。 有关可以检索供稿而无需知道其网址的方式的详细信息,请参阅参考指南中的在供稿间浏览

添加视频响应

检索视频响应链接之后,如上一节所示,您可以发布与视频(要将其标记为对原始视频的视频响应)对应的 VideoEntry

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

请注意,必须经过视频所有者批准后视频响应才能显示在 YouTube 上。

删除视频响应

如果您拥有使用视频响应链接检索的 VideoFeed 对象中列出的其中一个视频,则可以通过调用 Zend_Gdata_YouTube 服务对象上的 delete() 并传入要删除的条目,来删除作为视频响应的视频。

$yt->delete($videoEntryToBeDeleted);

标记视频

通过向 VideoEntry 对象的投诉链接发布 Atom 条目,可以添加对视频的投诉。以下代码显示标记视频的方式。

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

保存与收集视频

喜欢的视频

检索用户喜欢的视频

YouTube 用户可以选择将他们观看的视频标为喜欢的视频。以下网址为用户喜欢的视频供稿的常见位置。

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

要检索用户喜欢的视频,只需从 Zend_Gdata_YouTube 服务对象请求供稿即可。返回的供稿为常规视频供稿,其中包含 VideoEntry 对象。

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

注意:您还可以传入字符串 default 以检索目前已验证用户的喜欢的视频。

添加喜欢的视频

要添加喜欢的视频,请使用 Zend_Gdata_YouTube 服务对象的 insertEntry 方法将新喜欢的视频(常规 Zend_Gdata_YouTube_VideoEntry)发布到用户喜欢的视频的供稿。

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

删除喜欢的视频

要删除喜欢的视频,只需使用 Zend_Gdata_YouTube_VideoEntry 对象上的 delete() 方法即可。请确保从实际用户喜欢的视频的供稿中检索喜欢的视频。否则您将删除实际视频条目。

$favoriteVideoToBeDeleted->delete();

播放列表

每个 YouTube 用户都有一个相关的播放列表供稿,这是包含每个播放列表中视频之供稿的链接列表。

检索用户播放列表

要手动获取用户的所有播放列表,您可以使用以下网址:

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

注意:您还可以传入字符串 default 以检索目前已验证用户的喜欢的视频。

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

function printPlaylistListFeed($playlistListFeed, $showPlaylistContents)
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $playlistListFeed->title->text;
  }
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
  foreach ($playlistListFeed as $playlistListEntry) {
    echo 'Entry # ' . $count . "\n";
    printPlaylistListEntry($playlistListEntry, $showPlaylistContents);
    echo "\n";
    $count++;
  }
  echo "</pre>\n";
}

检索播放列表信息

指定 PlaylistListEntry,如上一实例中进行的检索,您可以使用以下代码获取并打印实际播放列表:

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, $tabs = "") 
{
  $yt = new Zend_Gdata_YouTube();
  $playlistVideoFeed = $yt->getPlaylistVideoFeed($playlistListEntry->getPlaylistVideoFeedUrl());
  foreach ($playlistVideoFeed as $playlistVideoEntry) {
    printVideoEntry($playlistVideoEntry, $tabs . "\t");
  }
}

函数 printPlaylistListEntry() 使用可选布尔参数 showPlaylistContents;如果该参数为真,则使用下一节定义的函数,每个播放列表中视频的列表也包含在输出中。

添加播放列表

要添加新播放列表,只需使用 Zend_Gdata_YouTube 服务对象创建一个播放列表,然后将其发布到用户的播放列表网址中。

$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/users/default/playlists';
try {
  $yt->insertEntry($newPlaylist, $postLocation);
} catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
}

更新播放列表

要更新播放列表,只需修改已检索的 Zend_Gdata_YouTube_PlaylistListEntry 对象,然后使用 save() 方法来保存您的更改。

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

将视频添加到播放列表

您可以通过使用 VideoEntry 对象将视频添加到播放列表。以下代码可以使用已知条目 ID 检索 VideoEntry,然后将其添加到与 PlaylistLinkEntry 对应的播放列表中。由于尚未指定位置,会将新视频添加到播放列表的末尾。

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

// create a new Zend_Gdata_PlaylistListEntry, passing in the underling DOMElement of the VideoEntry
$newPlaylistListEntry = $service->newPlaylistListEntry($videoEntryToAdd->getDOM());
$newPlaylistListEntry->description = $service->newDescription()->setText('Custom description');
$newPlaylistListEntry->title = $service->newTitle()->setText('Custom title');

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

请注意,上述代码可以指定视频的自定义标题和说明。这不是必需的,如果不指定则会使用视频的实际标题和说明。

编辑播放列表上的视频信息

您可以通过更新视频的 PlaylistVideoEntry 对象并调用其 update 方法,来修改播放列表中每个视频的自定义标题和说明。

// get a Zend_Gdata_PlaylistVideoEntry from the feed generated by $yt->getPlaylistVideoFeedUrl
$playlistVideoEntryToBeModified->setPosition($yt->newPosition(2));
$playlistVideoEntryToBeModified->setTitle($yt->newTitle('Updated title for my video'));

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

注意:如果您要将播放列表中视频的说明和标题更改回视频的原始标题和说明,您可以使用上述代码,然后只需传入 NULL 作为标题和说明即可。

从播放列表中删除视频

要从播放列表中删除视频,请使用 PlaylistListEntrydelete() 方法。

$playlistEntryToBeDeleted->delete();

删除播放列表

要删除播放列表,只需使用 Zend_Gdata_YouTube_PlaylistListEntry 对象上的 delete() 方法即可。

$playlistListEntryToBeDeleted->delete();

订阅

要获取频道列表、搜索列表和指定用户订阅的喜欢视频的列表,请使用以下网址:

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

注意:您还可以传入字符串 default 以检索目前已验证用户的喜欢的视频。

检索用户订阅

以下代码演示了检索与打印指定用户的 SubscriptionEntry 对象的列表的方式:

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";
}

添加订阅

您可以通过向已验证用户的订阅供稿中插入新的 SubscriptionEntry,来创建新的订阅。以下代码可以让已验证用户订阅“GoogleDevelopers”频道。

$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/users/'. $userName .'/subscriptions';
// and then post using $yt->insertEntry
try {
  $yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

您还可以订阅“GoogleDevelopers”用户的喜欢视频:

$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/users/default/subscriptions';
// and then post using $yt->insertEntry
try {
  $yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

最后,您还可以订阅特定搜索项。以下为订阅对有关“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/users/default/subscriptions';
try {
  $yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

请注意,以后版本的 PHP 客户端库将精选该功能。我们将提供自动生成并设置 yt:querystring 扩展元素的辅助方法。

删除订阅

要删除用户订阅,只需调用 SubscriptionEntry 对象上的 delete()

$subscriptionEntryToBeDeleted->delete();

启用用户交互

用户个人资料

检索用户的个人资料

要手动获取用户的 YouTube 个人资料,您可以使用以下网址:

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

您可以使用以下代码检索并打印用户的个人资料:

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";
}

请注意,可以使用字符串 default 代替用户名来表示“目前已验证用户”。客户端库只在 PHP 5.2 中才能使用过载魔术方法。如果您在使用 PHP 5.1,将需要修改上述调用。在这种情况下,需要将某些内容如 $userProfileEntry->getAge() 更改为 $userProfileEntry->getAge()->getTitle()

联系人

您可以从以下网址检索指定用户的联系人的列表:

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

检索用户联系人

以下代码演示了检索及打印指定用户的联系人列表的方式:

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";
}

添加联系人

要将新联系人添加为 Friend,请使用 Zend_Gdata_YouTube 服务对象的 insertEntry 方法。

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

接受/拒绝联系人

您可以通过更新对应 ContactEntry 的状态,接受或拒绝联系人。

要接受请求:

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

要拒绝请求,只需将值“rejected”传到 ContactEntry 的状态。

删除联系人

要删除联系人,只需调用 ContactEntry 对象上的 delete() 方法即可。

$contactToBeDeleted->delete();

讯息

接受彼此为联系人的 YouTube 用户之间可以互相发送讯息。通过 API 发送的所有讯息都必须包含 VideoEntry

检索用户讯息

要检索用户收件箱的内容,请向用户的收件箱网址发送已验证的请求:

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

以下实例可以打印已验证用户的收件箱的内容。

$inboxFeedUrl = 'http://gdata.youtube.com/feeds/api/users/username/inbox';
$inboxFeed = $yt->getFeed($inboxFeedUrl);

function printVideoMessageFeed($inboxFeed, $displayTitle = null) 
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $videoFeed->title->text;
  }
  echo '<h2>' . $displayTitle . "</h2>\n";
  echo "<pre>\n";
  
  foreach ($inboxFeed as $videoMessageEntry) {
    echo 'Entry # ' . $count . "\n";
    printVideoMessage($videoMessageEntry);
    echo "\n";
    $count++;
  }
  echo "</pre>\n";
}

function printVideoMessage($videoMessageEntry, $tabs = "") 
{
    echo $tabs . 'Subject: ' . $videoMessageEntry->getVideoTitle() . "\n";
    echo $tabs . "\tAuthor: " . $videoEntry->getAuthor() . "\n";
    echo $tabs . "\tMessage: " . $videoEntry->getVideoDescription() . "\n";
}

向用户发送讯息

要向用户发送讯息,请构建 VideoEntry 对象,并将其插入用户的收件箱供稿中。以下代码可以将包含视频的讯息发送到经 $receivingUser 变量识别的用户。要将视频插入讯息,请包含 video_id

$inboxUrl = 'http://gdata.youtube.com/feeds/api/users/' . $receivingUser . '/inbox';
$videoMessageEntry = $yt->newEntry();

// pass in the ID of the video to be included in your message (required)
$newMessage = $yt->newMediaEntry();
$newMessage->id = $yt->newId('video_id');
$newMessage->title = $yt->newTitle('message title');
$newMessage->extensionElements = array($yt->newDescription('message body'));

// insert the message
try {
  $yt->insertEntry($newMessage, $inboxUrl);
} catch (Zend_App_Excetion $e) {
  print $e->getMessage();
}

讯息的接收者必须是讯息发送者已接受的联系人。

删除讯息

要删除讯息,只需调用条目上的 delete() 即可。

$videoMessageEntryToBeDeleted->delete();

返回页首