Get all my videos (including private ones) using OAuth2 - php

I currently have something working where it gets all of my videos based on my Youtube username. Now I need to have it pull my private videos as well.
How I need everything to work is as I upload a video to Youtube it automatically embeds on my webpage which is password protected.
I created my API key and also used the Oauth 2.0 Sandbox and was able to retrieve all of the videos, including private but I do not know how to integrate the Oauth with my current coding which is below:
<?php
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/users/tprestinario/uploads';
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
?>
<h1><?php echo $sxml->title; ?></h1>
<?php
// iterate over entries in feed
foreach ($sxml->entry as $entry) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$watch = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$thumbnail = $attrs['url'];
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
$videoid = $yt->videoid[0];
?>
<div class="item">
<h1><?php echo $media->group->title; ?></h1>
<p><?php echo $media->group->description; ?></p>
<iframe width="560" height="315" src="http://www.youtube.com/embed/<?php echo $videoid; ?>" frameborder="0" allowfullscreen></iframe>
</div>
<?php
}
?>

If you use YouTube Data API V3 that would be much easier.
Here's a nice example for this use case.
"https://code.google.com/p/youtube-api-samples/source/browse/samples/php/my_uploads.php"

Related

Displaying playlist data from YouTube API v3

I am trying to use the YouTube v3 API to show all the videos from a particular YouTube playlist. Here is my code so far:
<?php
$playlistId = 'PLHGPqm6HHcedxhoMXo9m9yKqsOmOB_S0F';
$maxResults = 20;
$apiKey = 'APIKEYHERE';
$string = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId='.$playlistId.'&maxResults='.$maxResults.'&key='.$apiKey.''));
foreach($string['items'] as $item) {
echo $item['title'];
}
?>
I have used Postman to test the url and it is definitely getting data but when i try to echo any data it isn't showing.
I have learnt that Json decode will return stdclass by default json_decode php.net so you would have to replace foreach with this:
foreach($string->items as $item) {
echo $item->snippet->title;
}

Replacement for gdata

I have a URL like this, its contained in a php file to find stats about a video.
How should i be doing these now since gdata no longer works? I couldn't find it in the API!
('http://gdata.youtube.com/schemas/2007'); // get node for viewer statistics
http://gdata.youtube.com/feeds/api/videos/?q=
Im not quite sure what to do
-OLD CODE-
This is where my issue lies. I need to figure out how this is written with the new API,
$media = $entry->children('http://search.yahoo.com/mrss/'); // get nodes in media: namespace for media information
$attrs = $media->group->player->attributes(); // get video player URL
$watch = $attrs['url'];
$attrs = $media->group->thumbnail[0]->attributes(); // get video thumbnail
$thumbnail = $attrs['url'];
$yt = $media->children('http://gdata.youtube.com/schemas/2007'); // get <yt:duration> node for video length
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
$yt = $entry->children('http://gdata.youtube.com/schemas/2007'); // get <yt:stats> node for viewer statistics
$attrs = $yt->statistics->attributes();
$viewCount = $attrs['viewCount'];
$gd = $entry->children('http://schemas.google.com/g/2005'); // get <gd:rating> node for video ratings
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
}else{$rating = 0;}
$vid = preg_replace ('/&feature=youtube_gdata_player/','',$watch); // get video id
$vid = substr($vid, -11);
-OLD CODE WITH THE NEW API FORMAT FOR ONE PART-
<?php
error_reporting(0);
if ($_COOKIE['autoexp'] == 'on'){$autoexp = "showresult";}else{$autoexp = "hideresult";}
$query = $_POST['terms'];
$searchnum = $_COOKIE['snum'];
$searchurl = "https://www.googleapis.com/youtube/v3/search?q=".$query."&part=snippet&key=MYAPIKEYISHERE&max-results=50&format=5";
$feedURL = $searchurl; // set feed URL
$sxml = simplexml_load_file($feedURL); // read feed into SimpleXML object
$i = 0;
$i++;
$sn = 1;
if (empty($query)){
print '<tr><td><div style="margin:auto;padding-top:155px;width:300px;height:120px;text-align:center;"><img src="images/logo.png" height="100"></div></td></tr>';
}
foreach ($sxml->entry as $entry) { // iterate over entries in feed
if ($sn <= $searchnum){
$media = $entry->children('http://search.yahoo.com/mrss/'); // get nodes in media: namespace for media information
$attrs = $media->group->player->attributes(); // get video player URL
$watch = $attrs['url'];
$attrs = $media->group->thumbnail[0]->attributes(); // get video thumbnail
$thumbnail = $attrs['url'];
$yt = $media->children('http://gdata.youtube.com/schemas/2007'); // get <yt:duration> node for video length
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
$yt = $entry->children('http://gdata.youtube.com/schemas/2007'); // get <yt:stats> node for viewer statistics
$attrs = $yt->statistics->attributes();
$viewCount = $attrs['viewCount'];
$gd = $entry->children('http://schemas.google.com/g/2005'); // get <gd:rating> node for video ratings
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
}else{$rating = 0;}
$vid = preg_replace ('/&feature=youtube_gdata_player/','',$watch); // get video id
$vid = substr($vid, -11);
if ($length <= 600){
$i++;
print " <tr class=\"d".($i & 1)."\"><td>";
?>
<table class="searchresults">
<tr><td>
<b>- <?php echo $media->group->title; ?></b>
</td><td WIDTH="110">
<div style="padding-left:7px;"><B>Length : </B> <?=substr(gmdate("i:s", '00'.$length),1)?></div>
</td><td width="130" align="center">
<IMG SRC="images/mp3.png" onmouseover="this.src='images/mp32.png';" onmouseout="this.src='images/mp3.png';" title="Get MP3">
</td></tr>
</table>
<div id="infodiv-<?=$vid?>" class="<?=$autoexp?>">
<table class="searchresults" style="height:25px;" >
<tr><td>
<div class="menubar2" style="position:relative;top:-5px;">
<div style="float:left;padding-left:10px;position:absolute;margin-top:-1px;z-index:5;"><img src="<?=$thumbnail?>" height="42" border="1"></div>
<div style="float:left;text-align:left;padding-left:85px;color:#333333;"><b>Author:</b> <?php echo $entry->author->name; ?><div style="color:#000000;padding-top:4px;padding-bottom:0px"><small><?=$viewCount?> Views</small></div></div>
<div style="float:right;margin-right:20px;margin-top:9px;border-style:solid;border-width:1px;"><object width= "217" height="30"><param name="movie" value="http://www.youtube.com/v/<?=$vid?>&rel=0&fs=0&theme=light&showinfo=0&modestbranding=1&autohide=0&color=red"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/<?=$vid?>&rel=0&fs=0&theme=light&showinfo=0&modestbranding=1&autohide=0&color=red" type="application/x-shockwave-flash" allowfullscreen="false" width="217" height="30" allowscriptaccess="always"></embed></object></div>
</div>
</td></tr>
</table>
</div>
</td></tr>
<?php
$sn++;
}else{}
}else{}
}
?>
</table>
How would I go about making this work again?
For video statistics you can request
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id={VIDEO_ID}&key={YOUR_API_KEY}
For more info about what kind of data you can get from a video, read this.
You can even try this endpoint using this.
Yes, that is because you need to use their official API now and obtain your developer key(its free) and download the php Google service libraries.
https://github.com/google/google-api-php-client
This is an example how you get info from a video in PHP
//You need to download these libraries
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
$client = new Google_Client();
$client->setDeveloperKey("YOURDEVELOPERKEYHERE");
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// YouTube object used to make all API requests.
$youtube = new Google_Service_Youtube($client);
$videoIds = "a0nii7mxpFc"; //comma separated if > 1 video
$listResponse = $youtube->videos->listVideos("id,snippet,contentDetails,statistics",array('id' => $videoIds,'maxResults'=>50));
$videoList = $listResponse['items'];
foreach ($videoList as $key => $value){
$video = $videoList[$key];
//Here are the stats
echo $video['statistics']['likeCount'];
echo $video['statistics']['dislikeCount'];
}

Namespace in MRSS feed using simplexml PHP Script

Tried to research what I'm doing wrong here, but no luck so far. I want to pull the links and URLs in this MRSS feed using this script, but it's not working. Thought all I needed to do was use namespaces to get the child elements out, but no luck:
<?php
$html = "";
$url = "http://feeds.nascar.com/feeds/video?command=search_videos&media_delivery=http&custom_fields=adtitle%2cfranchise&page_size=100&sort_by=PUBLISH_DATE:DESC&token=217e0d96-bd4a-4451-88ec-404debfaf425&any=franchise:%20Preview%20Show&any=franchise:%20Weekend%20Top%205&any=franchise:Up%20to%20Speed&any=franchise:Press%20Pass&any=franchise:Sprint%20Cup%20Practice%20Clips&any=franchise:Sprint%20Cup%20Highlights&any=franchise:Sprint%20Cup%20Final%20Laps&any=franchise:Sprint%20Cup%20Victory%20Lane&any=franchise:Sprint%20Cup%20Post%20Race%20Reactions&any=franchise:All%20Access&any=franchise:Nationwide%20Series%20Qualifying%20Clips&any=franchise:Nationwide%20Series%20Highlights&any=franchise:Nationwide%20Series%20Final%20Laps&any=franchise:Nationwide%20Series%20Victory%20Lane&any=franchise:Nationwide%20Series%20Post%20Race%20Reactions&any=franchise:Truck%20Series%20Qualifying%20Clips&any=franchise:Truck%20Series%20Highlights&any=franchise:Truck%20Series%20Final%20Laps&any=franchise:Truck%20Series%20Victory%20Lane&any=franchise:Truck%20Series%20Post%20Race%20Reactions&output=mrss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 50; $i++){ // will return the 50 most recent videos
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$url = $xml->channel->item[$i]->children($namespaces['media'])->url;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=//my API token goes here &bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
I take it this isn't the right approach:
$url = $xml->channel->item[$i]->children($namespaces['media'])->url;
What am I doing wrong here?
Thanks for any and all help!
MD
SimpleXML is deceptively named as it is more difficult to use than DOMDocument or the other PHP XML extensions. To get the URL, you'll need to access the url attribute of the media:content node:
<media:content duration="95" medium="video" type="video/mp4"
url="http://brightcove.meta.nascar.com.edgesuite.net/vod/etc"/>
Target the first <media:content> node using
$xml->channel->item[$i]->children($namespaces['media'])->content[0]
and get its attributes:
$m_attrs =
$xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
You can then access the url attribute:
echo "URL: " . $m_attrs["url"] . "\n";
Your code should thus be:
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$m_attrs = $xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
$url = $m_attrs["url"];
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p> (etc.)";

Youtube Api to get video description with video id

I am trying to get discriptiobn from youtube using api .... but i dont no where am i wrong its not getting for single video . but if i try playlist its working fine, not with video id
Here is my code
error_reporting(E_ALL);
$feedURL = 'https://gdata.youtube.com/feeds/api/playlists/'.$id.'?v=2&prettyprint=true';
$sxml = simplexml_load_file($feedURL);
echo $feedURL.'</br>';
foreach ($sxml->entry as $entry)
{
echo $media->group->description;
}
Above code is working with playlist ... but if i try one video its not working:
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$id.'?v=2&alt=json&prettyprint=true';
$sxml = simplexml_load_file($feedURL);
echo $feedURL.'</br>';
foreach ($sxml->entry as $entry)
{
echo $media->group->description;
}
If you call YouTube api with 'alt=json' parameter, the response will be formatted as JSON not XML. So you should use:
$response = json_decode(file_get_contents('... API URL ...'), true);
And then 'description' can be accessed with:
$response['entry']['media$group']['media$description']['$t']

SimpleXML - "Node no longer exists"

I'm trying to get the video data from this youtube playlist feed and add the interesting data to an array and use that later, but as you can see from the feed some videolinks are "dead" and that results in problems for my code.
The error I get is "Node no longer exists" when I try to access $attrs['url']. I've tried for hours to find a way to check if the node exists before I access it but I have no luck.
If anyone could help me to either parse the feed some other way with the same result or create a if-node-exists check that works I would be most happy. Thank you in advance
$url = 'http://gdata.youtube.com/feeds/api/playlists/18A7E36C33EF4B5D?v=2';
$sxml = simplexml_load_file($url);
$i = 0;
$videoobj;
foreach ($sxml->entry as $entry) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$videoobj[$i]['url'] = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$videoobj[$i]['thumb'] = $attrs['url'];
$videoobj[$i]['title'] = $media->group->title;
$i++;
}
if ($media->group->thumbnail && $media->group->thumbnail[0]->attributes()) {
$attrs = $media->group->thumbnail[0]->attributes();
$videoobj[$i]['thumb'] = strval($attrs['url']);
$videoobj[$i]['title'] = strval($media->group->title);
}
SimpleXML's methods always return objects, which are themselves linked to the original document (some internal thingy related to libxml.) If you want to store that data for later use, cast it as a string, like this:
$videoobj[$i]['url'] = (string) $attrs['url'];
$videoobj[$i]['thumb'] = (string) $attrs['url'];
$videoobj[$i]['title'] = (string) $media->group->title;

Categories