Using the YouTube Data API - Manual - Documentation - Zend ...
文章推薦指數: 80 %
See the » YouTube API reference guide for a detailed list of available feeds. Searching for videos by metadata. You can retrieve a list of videos that match ...
Togglenavigation
ABOUT
INSTALL
DOCUMENTATION
TRAINING
BLOG
PARTICIPATE
Documentation
Caution:Thedocumentationyouareviewingis
foranolderversionofZendFramework.
Youcanfindthedocumentationofthecurrentversionat:
https://docs.zendframework.com/
UsingtheYouTubeDataAPI-Zend_Gdata
UsingPicasaWebAlbumsCatchingGdataExceptionsUsingtheYouTubeDataAPI
TheYouTubeDataAPIoffersreadandwriteaccesstoYouTube'scontent.
UserscanperformunauthenticatedrequeststoGoogleDatafeedsto
retrievefeedsofpopularvideos,comments,publicinformationabout
YouTubeuserprofiles,userplaylists,favorites,subscriptionsandsoon.
FormoreinformationontheYouTubeDataAPI,pleaserefer
totheofficial»PHP
Developer'sGuideoncode.google.com.
Authentication
TheYouTubeDataAPIallowsread-onlyaccesstopublicdata,which
doesnotrequireauthentication.Foranywriterequests,auser
needstoauthenticateeitherusingClientLoginorAuthSubauthentication.Pleaserefer
tothe»Authentication
sectioninthePHPDeveloper'sGuideformoredetail.
DeveloperKeysandClientID
AdeveloperkeyidentifiestheYouTubedeveloperthatissubmitting
anAPIrequest.AclientIDidentifiesyourapplicationforlogging
anddebuggingpurposes.Pleasevisit»http://code.google.com/apis/youtube/dashboard/
toobtainadeveloperkeyandclientID.Theexamplebelowdemonstrateshowtopassthe
developerkeyandclientIDtothe»Zend_Gdata_YouTube
serviceobject.
Example#1PassingaDeveloperKeyandClientIDtoZend_Gdata_YouTube
$yt=newZend_Gdata_YouTube($httpClient,
$applicationId,
$clientId,
$developerKey);
Retrievingpublicvideofeeds
TheYouTubeDataAPIprovidesnumerousfeedsthatreturnalistof
videos,suchasstandardfeeds,relatedvideos,videoresponses,
user'suploads,anduser'sfavorites.Forexample,the
user'suploadsfeedreturnsallvideosuploadedbyaspecificuser.Seethe»YouTube
APIreferenceguideforadetailedlistofavailable
feeds.
Searchingforvideosbymetadata
Youcanretrievealistofvideosthatmatchspecified
searchcriteria,usingtheYouTubeQueryclass.Thefollowingquery
looksforvideoswhichcontaintheword"cat"intheir
metadata,startingwiththe10thvideoanddisplaying20
videosperpage,orderedbytheviewcount.
Example#2Searchingforvideos
$yt=newZend_Gdata_YouTube();
$query=$yt->newVideoQuery();
$query->videoQuery='cat';
$query->startIndex=10;
$query->maxResults=20;
$query->orderBy='viewCount';
echo$query->queryUrl."\n";
$videoFeed=$yt->getVideoFeed($query);
foreach($videoFeedas$videoEntry){
echo"---------VIDEO----------\n";
echo"Title:".$videoEntry->getVideoTitle()."\n";
echo"\nDescription:\n";
echo$videoEntry->getVideoDescription();
echo"\n\n\n";
}
Formoredetailsonthedifferentqueryparameters,pleaserefertothe»
ReferenceGuide.Theavailablehelperfunctionsin»Zend_Gdata_YouTube_VideoQuery
foreachoftheseparametersaredescribedinmoredetailinthe»PHP
Developer'sGuide.
Searchingforvideosbycategoriesandtags/keywords
Searchingforvideosinspecificcategoriesisdonebygeneratinga»specially
formattedURL.Forexample,tosearchfor
comedyvideoswhichcontainthekeyworddog:
Example#3Searchingforvideosinspecificcategories
$yt=newZend_Gdata_YouTube();
$query=$yt->newVideoQuery();
$query->category='Comedy/dog';
echo$query->queryUrl."\n";
$videoFeed=$yt->getVideoFeed($query);
Retrievingstandardfeeds
TheYouTubeDataAPIhasanumberof»standard
feeds.Thesestandardfeedscanberetrievedas»Zend_Gdata_YouTube_VideoFeed
objectsusingthespecifiedURLs,usingthepredefinedconstants
withinthe»Zend_Gdata_YouTube
class(Zend_Gdata_YouTube::STANDARD_TOP_RATED_URIforexample)or
usingthepredefinedhelpermethods(seecodelistingbelow).
Toretrievethetopratedvideosusingthehelpermethod:
Example#4Retrievingastandardvideofeed
$yt=newZend_Gdata_YouTube();
$videoFeed=$yt->getTopRatedVideoFeed();
Therearealsoqueryparameterstospecifythetimeperiod
overwhichthestandardfeediscomputed.
Forexample,toretrievethetopratedvideosfortoday:
Example#5UsingaZend_Gdata_YouTube_VideoQuerytoRetrieveVideos
$yt=newZend_Gdata_YouTube();
$query=$yt->newVideoQuery();
$query->setTime('today');
$videoFeed=$yt->getTopRatedVideoFeed($query);
Alternatively,youcouldjustretrievethefeedusingthe
URL:
Example#6RetrievingavideofeedbyURL
$yt=newZend_Gdata_YouTube();
$url='http://gdata.youtube.com/feeds/standardfeeds/top_rated?time=today'
$videoFeed=$yt->getVideoFeed($url);
Retrievingvideosuploadedbyauser
Youcanretrievealistofvideosuploadedbyaparticularuser
usingasimplehelpermethod.Thisexampleretrievesvideos
uploadedbytheuser'liz'.
Example#7Retrievingvideosuploadedbyaspecificuser
$yt=newZend_Gdata_YouTube();
$videoFeed=$yt->getUserUploads('liz');
Retrievingvideosfavoritedbyauser
Youcanretrievealistofauser'sfavoritevideos
usingasimplehelpermethod.Thisexampleretrievesvideos
favoritedbytheuser'liz'.
Example#8Retrievingauser'sfavoritevideos
$yt=newZend_Gdata_YouTube();
$videoFeed=$yt->getUserFavorites('liz');
Retrievingvideoresponsesforavideo
Youcanretrievealistofavideo'svideoresponses
usingasimplehelpermethod.Thisexampleretrievesvideo
responseforavideowiththeID'abc123813abc'.
Example#9Retrievingafeedofvideoresponses
$yt=newZend_Gdata_YouTube();
$videoFeed=$yt->getVideoResponseFeed('abc123813abc');
Retrievingvideocomments
ThecommentsforeachYouTubevideocanberetrievedin
severalways.Toretrievethecommentsforthevideowith
theID'abc123813abc',usethefollowingcode:
Example#10RetrievingafeedofvideocommentsfromavideoID
$yt=newZend_Gdata_YouTube();
$commentFeed=$yt->getVideoCommentFeed('abc123813abc');
foreach($commentFeedas$commentEntry){
echo$commentEntry->title->text."\n";
echo$commentEntry->content->text."\n\n\n";
}
Commentscanalsoberetrievedforavideoifyouhaveacopyofthe»Zend_Gdata_YouTube_VideoEntry
object:
Example#11RetrievingaFeedofVideoCommentsfromaZend_Gdata_YouTube_VideoEntry
$yt=newZend_Gdata_YouTube();
$videoEntry=$yt->getVideoEntry('abc123813abc');
//wedon'tknowthevideoIDinthisexample,butwedohavetheURL
$commentFeed=$yt->getVideoCommentFeed(null,
$videoEntry->comments->href);
Retrievingplaylistfeeds
TheYouTubeDataAPIprovidesinformationaboutusers,including
profiles,playlists,subscriptions,andmore.
Retrievingtheplaylistsofauser
Thelibraryprovidesahelpermethodtoretrieve
theplaylistsassociatedwithagivenuser.Toretrievethe
playlistsfortheuser'liz':
Example#12Retrievingtheplaylistsofauser
$yt=newZend_Gdata_YouTube();
$playlistListFeed=$yt->getPlaylistListFeed('liz');
foreach($playlistListFeedas$playlistEntry){
echo$playlistEntry->title->text."\n";
echo$playlistEntry->description->text."\n";
echo$playlistEntry->getPlaylistVideoFeedUrl()."\n\n\n";
}
Retrievingaspecificplaylist
Thelibraryprovidesahelpermethodtoretrieve
thevideosassociatedwithagivenplaylist.Toretrievethe
playlistsforaspecificplaylistentry:
Example#13Retrievingaspecificplaylist
$feedUrl=$playlistEntry->getPlaylistVideoFeedUrl();
$playlistVideoFeed=$yt->getPlaylistVideoFeed($feedUrl);
Retrievingalistofauser'ssubscriptions
Ausercanhaveseveraltypesofsubscriptions:channel
subscription,tagsubscription,orfavoritessubscription.A»Zend_Gdata_YouTube_SubscriptionEntry
isusedtorepresentindividualsubscriptions.
Toretrieveallsubscriptionsfortheuser'liz':
Example#14Retrievingallsubscriptionsforauser
$yt=newZend_Gdata_YouTube();
$subscriptionFeed=$yt->getSubscriptionFeed('liz');
foreach($subscriptionFeedas$subscriptionEntry){
echo$subscriptionEntry->title->text."\n";
}
Retrievingauser'sprofile
Youcanretrievethepublicprofileinformation
foranyYouTubeuser.Toretrievetheprofile
fortheuser'liz':
Example#15Retrievingauser'sprofile
$yt=newZend_Gdata_YouTube();
$userProfile=$yt->getUserProfile('liz');
echo"username:".$userProfile->username->text."\n";
echo"age:".$userProfile->age->text."\n";
echo"hometown:".$userProfile->hometown->text."\n";
UploadingVideostoYouTube
Pleasemakesuretoreviewthediagramsinthe»protocol
guideoncode.google.comforahigh-level
overviewoftheuploadprocess.Uploadingvideoscanbedoneinoneof
twoways:eitherbyuploadingthevideodirectlyorbysendingjustthevideo
meta-dataandhavingauseruploadthevideothroughanHTMLform.
Inordertouploadavideodirectly,youmustfirstconstructanew»Zend_Gdata_YouTube_VideoEntry
objectandspecifysomerequiredmeta-data.Thefollowingexampleshowsuploadingthe
Quicktimevideo"mytestmovie.mov"toYouTubewiththefollowingproperties:
Metadatausedinthecode-samplebelow
Property
Value
Title
MyTestMovie
Category
Autos
Keywords
cars,funny
Description
Mydescription
Filename
mytestmovie.mov
FileMIMEtype
video/quicktime
Videoprivate?
FALSE
Videolocation
37,-122(lat,long)
DeveloperTags
mydevelopertag,anotherdevelopertag
Thecodebelowcreatesablank»Zend_Gdata_YouTube_VideoEntry
tobeuploaded.A»Zend_Gdata_App_MediaFileSource
objectisthenusedtoholdtheactualvideofile.Underthehood,the»Zend_Gdata_YouTube_Extension_MediaGroup
objectisusedtoholdallofthevideo'smeta-data.Ourhelpermethodsdetailedbelow
allowyoutojustsetthevideometa-datawithouthavingtoworryaboutthemediagroup
object.The$uploadUrlisthelocationwherethenewentrygetspostedto.
Thiscanbespecifiedeitherwiththe$userNameofthe
currentlyauthenticateduser,or,alternatively,youcansimplyusethe
string'default'torefertothecurrentlyauthenticateduser.
Example#16Uploadingavideo
$yt=newZend_Gdata_YouTube($httpClient);
$myVideoEntry=newZend_Gdata_YouTube_VideoEntry();
$filesource=$yt->newMediaFileSource('mytestmovie.mov');
$filesource->setContentType('video/quicktime');
$filesource->setSlug('mytestmovie.mov');
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle('MyTestMovie');
$myVideoEntry->setVideoDescription('MyTestMovie');
//NotethatcategorymustbeavalidYouTubecategory!
$myVideoEntry->setVideoCategory('Comedy');
//Setkeywords,notethatthismustbeacommaseparatedstring
//andthateachkeywordcannotcontainwhitespace
$myVideoEntry->SetVideoTags('cars,funny');
//Optionallysetsomedevelopertags
$myVideoEntry->setVideoDeveloperTags(array('mydevelopertag',
'anotherdevelopertag'));
//Optionallysetthevideo'slocation
$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);
//UploadURIforthecurrentlyauthenticateduser
$uploadUrl=
'http://uploads.gdata.youtube.com/feeds/users/default/uploads';
//Trytouploadthevideo,catchingaZend_Gdata_App_HttpException
//ifavailableorjustaregularZend_Gdata_App_Exception
try{
$newEntry=$yt->insertEntry($myVideoEntry,
$uploadUrl,
'Zend_Gdata_YouTube_VideoEntry');
}catch(Zend_Gdata_App_HttpException$httpException){
echo$httpException->getRawResponseBody();
}catch(Zend_Gdata_App_Exception$e){
echo$e->getMessage();
}
Touploadavideoasprivate,simplyuse:$myVideoEntry->setVideoPrivate();priorto
performingtheupload.$videoEntry->isVideoPrivate()canbeusedtocheckwhethera
videoentryisprivateornot.
Browser-basedupload
Browser-baseduploadingisperformedalmostidenticallytodirectuploading,
exceptthatyoudonotattacha»Zend_Gdata_App_MediaFileSource
objecttothe»Zend_Gdata_YouTube_VideoEntry
youareconstructing.Insteadyousimplysubmitallofyourvideo'smeta-datatoreceive
backatokenelementwhichcanbeusedtoconstructanHTMLupload
form.
Example#17Browser-basedupload
$yt=newZend_Gdata_YouTube($httpClient);
$myVideoEntry=newZend_Gdata_YouTube_VideoEntry();
$myVideoEntry->setVideoTitle('MyTestMovie');
$myVideoEntry->setVideoDescription('MyTestMovie');
//NotethatcategorymustbeavalidYouTubecategory
$myVideoEntry->setVideoCategory('Comedy');
$myVideoEntry->SetVideoTags('cars,funny');
$tokenHandlerUrl='http://gdata.youtube.com/action/GetUploadToken';
$tokenArray=$yt->getFormUploadToken($myVideoEntry,$tokenHandlerUrl);
$tokenValue=$tokenArray['token'];
$postUrl=$tokenArray['url'];
Theabovecodeprintsoutalinkandatokenthatisusedtoconstructan
HTMLformtodisplayintheuser'sbrowser.Asimpleexampleformis
shownbelowwith$tokenValuerepresentingthecontentofthereturnedtokenelement,
asshownbeingretrievedfrom$myVideoEntryabove.Inorderfortheuser
toberedirectedtoyourwebsiteaftersubmittingtheform,makesureto
appenda$nextUrlparametertothe$postUrlabove,whichfunctionsinthe
samewayasthe$nextparameterofanAuthSublink.Theonlydifferenceis
thathere,insteadofasingle-usetoken,astatusandanidvariableare
returnedintheURL.
Example#18Browser-basedupload:CreatingtheHTMLform
//placetoredirectuserafterupload
$nextUrl='http://mysite.com/youtube_uploads';
$form='
延伸文章資訊
- 1Using the YouTube Data API - Manual - Documentation - Zend ...
See the » YouTube API reference guide for a detailed list of available feeds. Searching for video...
- 2Good documentation - the YouTube Data API - LinkedIn
The primary Reference page provided a brief overview of the API. YouTube Data API Reference page ...
- 3Is youtube data api totally free - Stack Overflow
- 4Retrieving Youtube video information from Google APIs using ...
- 5youtube_api - Rust - Docs.rs
API documentation for the Rust `youtube_api` crate.