How to work with youtube api V3 - api

I need help with youtube API V3.
as when on the browser I type:
https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=Titanic%201997%20Official%20Trailer&key=
it's show return values.
However I am trying to collect the array from php.
How can I use GET https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=Titanic%201997%20Official%20Trailer&key= in php so I get the result in php?
or is there any option to get the search result in a rss feed format.
Thanks in advance

Make a simple video search on YouTube API and you will get video title, description, video id and image source so best approach full code is given below.
<?php
error_reporting(0);
$search = "Search Query"; // Search Query
$api = "YouTube API Key"; // YouTube Developer API Key
$results = 10; // Max results
$link = "https://www.googleapis.com/youtube/v3/search?safeSearch=moderate&order=relevance&part=snippet&q=".urlencode($search). "&maxResults=$results&key=". $api;
$video = file_get_contents($link);
$video = json_decode($video, true);
foreach ($video['items'] as $data){
$title = $data['snippet']['title'];
$description = $data['snippet']['title'];
$vid = $data['id']['videoId'];
$image = "https://i.ytimg.com/vi/$vid/default.jpg";
// Output Title/Description/Image URL If Video ID exist
if($vid){
echo "Title: $title<br />Description: $description<br />Video ID: $vid<br />Image URL: $image<hr>";
}
}
?>

Related

Optimisation of google api requests to retrieve data from youtube videos

I'm trying to build a website with a section that displays the last video of a youtube channel and the thumbnails and titles of the next 9 most recent videos. The problem I'm having is that I consume the quota of requests just by testing the website.
To get this information I use Google's API. I retrieve the last 10 videos of the channel as follows:
<?PHP
include('global_variables.php');
$randomNumber = rand(2,10);
$randomKey = "api.key$randomNumber";
$data = file_get_contents("https://www.googleapis.com/youtube/v3/search?key=".$GLOBALS['api_key']."&part=snippet&channelId=".$GLOBALS['channel_id']."&order=date&maxResults=".$GLOBALS['videos_in_playlist']);
$json = json_decode($data);
echo $data;
?>
I call this PHP file in these ways:
// TO LOAD PLAYING YOUTUBE VIDEO
function loadVideo(iframe) {
$.getJSON("load_playing_video.php",
function(data) {
var videoNumber = (iframe.getAttribute('vnum') ? Number(iframe.getAttribute('vnum')) : 0);
iframe.setAttribute("src", "https://youtube.com/embed/" + data.items[videoNumber].id.videoId+ "?controls=1&autoplay=1&color=white");
// PLACE VIDEO TITLE
$("#playing-video-title").html(data.items[videoNumber].snippet.title);
// PLACE VIDEO DESCRIPTION
$("#playing-video-description").html(data.items[videoNumber].snippet.description);
}
);
}
loadVideo(document.querySelector("#playing-video"));
// TO LOAD THUMBNAILS AND TITLES ON SIDEBAR
$.getJSON("load_playing_video.php",
function(data) {
for (var index = 0; index < <?php echo $GLOBALS['videos_in_playlist']?>; index++) {
var videoImage = data.items[index].snippet.thumbnails.default.url;
var title = data.items[index].snippet.title;
var imgId = "#playlist-thumbnail" + index;
var titleId = "#playlist-title" + index;
document.querySelector(imgId).setAttribute("src",videoImage);
document.querySelector(titleId).innerHTML = title;
}
}
);
I was hoping someone could help me optimise the number of requests I do.
And if someone knows how I could increase the quota of requests (even if I have to pay) I would really appreciate some guidelines.
Thank you!!

How to display playback_count for a user using the SoundCloud API

I am trying to display the total track views ("playback_count") for a specific SoundCloud user using the SoundCloud API.
According to the API documentation I get the info using the below function call:
http://api.soundcloud.com/tracks/13158665.json?client_id=YOUR_CLIENT_ID
This is fine because it displays the number "13158665".
What is this number? Is it the trackid?
I need to get the "playback_count" for a user using the users username.
I tried getting the UserId from the Username using this:
$soundcloud_playsAPI = "MY_SOUNDCLOUD_API_KEY";
/* Get the SoundCloud UserId from the username */
$json = wp_remote_get("http://api.soundcloud.com/users/jwagener.json?client_id=".$soundcloud_playsAPI);
$soundcloudData = json_decode($json['body'], true);
$soundcloud_userid = $soundcloudData['id'];
This returns the UserId: 3207181
Now I tried to substitute that response into the previous URL to get the "playback_count" but it failed.
$json = wp_remote_get("http://api.soundcloud.com/tracks/3207181.json?client_id=".$soundcloud_playsAPI);
$soundcloudPlaysData = json_decode($json['body'], true);
echo $soundcloudPlaysData['playback_count'];
Any guidance would be greatly appreciated.
Thanks.
The first number is the id of a track, the second number is the id of a user.
Now that you have the user id, you will need to fetch each of their tracks and tally how many times they have been played
First, get the id numbers for all tracks made by the user
GET: /users/{id}/tracks: list of tracks of the user
$json = wp_remote_get("http://api.soundcloud.com/users/3207181/tracks.json?client_id=".$soundcloud_playsAPI);
Now you have a list of track IDs so you will need to get each of those tracks and save the playback_count of each
$json = wp_remote_get("http://api.soundcloud.com/tracks/track-id-here.json?client_id=".$soundcloud_playsAPI);
$soundcloudPlaysData = json_decode($json['body'], true);
echo $soundcloudPlaysData['playback_count'];
Here is the full solution:
function listPlays()
{SC.initialize({ client_id: 'YOUR ID HERE'});
// Get the SoundCloud UserId from the username
var userName="jwagener";
SC.get("/users/"+userName, function (users)
{console.log(users.id);
var myId=users.id;
getTracks(myId);
});
var getTracks=function (myId)
{var totalPlays=0;
SC.get("/users/"+myId+"/tracks", function(getTracks)
{for (var key in getTracks) //get each track and look at it's playback_count
{console.log(getTracks[key].title+" "+getTracks[key].playback_count);
totalPlays+=getTracks[key].playback_count; //add the playback count for this track to the total
}
console.log("Total Plays for all tracks: "+totalPlays);
});
};
};

Yii + Zend gdata. Youtube upload

I want to upload videos with next way:
I just upload file to server (as usual)
My server-side Yii-application takes that video and uploads it on Youtube from a special account on youTube
What do i have:
My YouTube (google) account name and email. "name" or "name#gmail.com"
My password
A developer Key, which I found in Google's "Product Dashboard"
A name of the application, which names 'myapp':
Product Dashboard: myapp
So, I read some docs in google and decided that best way for me is to use ClientLogin auth type, because I have only one account to use and I have all necessary data. I found an example for ZendFramework's GData and I imported it into my Yii application.
I specially simplified the code just to upload one single video from /upload directory to test that it works. I expect to find a video in my YT account uploaded. Of course there is no video and here I am :-) Complete code of the action is below:
Yii::import('application.vendors.*');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
$yt_user = 'myYTname';
$yt_pass = 'myYTpass';
$yt_source = 'myapp';
$yt_api_key = 'veryVERYlongKEYhere';
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $yt_user,
$password = $yt_pass,
$service = 'youtube',
$client = null,
$source = $yt_source,
$loginToken = null,
$loginCaptcha = null,
$authenticationURL
);
$yt = new Zend_Gdata_YouTube($httpClient, $yt_source, null, $yt_api_key);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource(Yii::getpathOfAlias('webroot').'/upload/videos/video.mp4');
$filesource->setContentType('video/mp4');
$filesource->setSlug('video.mp4');
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie description');
$myVideoEntry->setVideoCategory('Autos');
$myVideoEntry->SetVideoTags('cars, funny');
$myVideoEntry->setVideoDeveloperTags(array('mydevtag', 'anotherdevtag'));
$uploadUrl = "http://uploads.gdata.youtube.com/feeds/api/users/{$yt_user}/uploads";
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();
}
As you can see, there is a lot of default code from the official example. But it doesn't work. Noone echo shows me information. But when I deleted try-catch, I got an error:
Zend_Gdata_App_HttpException
Read timed out after 10 seconds
So, this problem is solved by myself :)
First of all: don't try to upload from localhost!
Then in my case I got an error, that I didn't say my dev-key! So, if you got the same error, try to change this:
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
by adding the 4th parameter - extra headers:
$yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry', array(
'X-GData-Key' => 'key=yourBIGbigBIGdeveloperKEYhere'
));
Good luck and have fun with youtube API!

Youtube API: losing data via curl in PHP?

I'm sure that this is likely a simple solution, but I can't see my error. I'm making an API call to youtube to get some basic information on a youtube video using the video's ID; specifically what I want is the (1) title, (2) description, (3) tags, and (4) thumbnail.
When I load an API url via my web browser, I see all the data. I don't want to paste the entire response in this question, but paste the following url in your browser and you'll see what I see: http://gdata.youtube.com/feeds/api/videos/_83A00a5mG4
If you look closely you'll see media:thumbnail, media:keywords, content, etc. Everything I want is there. Now the troubles...
When I load this same url through the following functions (which I copied from the Vimeo api...), the thumbnail and keywords simply aren't there.
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
// youtube_get_ID is defined elsewhere...
$request_url = "http://gdata.youtube.com/feeds/api/videos/" . youtube_get_ID($url);
$video_data = simplexml_load_string(curl_get($request_url));
These functions do give me a response with some data, but the keywords and thumbnail are missing. Could anyone please tell me why my thumbnail and keywords are missing? Thank you for any help!
Here's the link for documentation on this.
Here's a function I wrote:
function get_youtube_videos($max_number, $user_name) {
$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/' . $user_name . '/uploads?max-results=' . $max_number);
$server_time = $xml->updated;
$return = array();
foreach ($xml->entry as $video) {
$vid = array();
$vid['id'] = substr($video->id,42);
$vid['title'] = $video->title;
$vid['date'] = $video->published;
//$vid['desc'] = $video->content;
// get nodes in media: namespace for media information
$media = $video->children('http://search.yahoo.com/mrss/');
// get the video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$vid['length'] = $attrs['seconds'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$vid['thumb'] = $attrs['url'];
// get <yt:stats> node for viewer statistics
$yt = $video->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$vid['views'] = $attrs['viewCount'];
array_push($return, $vid);
}
return $return;
}
And here's the implementation:
$max_videos = 9;
$videos = get_youtube_videos($max_videos, 'thelonelyisland');
foreach($videos as $video) {
echo $video['title'] . '<br/>';
echo $video['id'] . '<br/>';
echo $video['date'] . '<br/>';
echo $video['views'] . '<br/>';
echo $video['thumb'] . '<br/>';
echo $video['length'] . '<br/>';
echo '<hr/>';
}

Ebay API with description

How do I get the Ebay API to return a description?
I have some code that makes an API call as follows:
http://svcs.ebay.com/services/search/FindingService/v1?
callname=findItemsAdvanced&
responseencoding=XML&
appid=appid&
siteid=0&
version=525&
QueryKeywords=keywords;
It returns items, but it's missing the full description text. I'm not seeing the next step to ask for the detailed descriptions.
You have to use Shopping API, for instance: http://developer.ebay.com/DevZone/shopping/docs/CallRef/GetSingleItem.html#sampledescriptionitemspecifics
I use following (very simple function to get Item detail from ebay):
function eBayGetSingle($ItemID){
$URL = 'http://open.api.ebay.com/shopping';
//change these two lines
$compatabilityLevel = 967;
$appID = 'YOUR_APP_ID_HERE';
//you can also play with these selectors
$includeSelector = "Details,Description,TextDescription,ShippingCosts,ItemSpecifics,Variations,Compatibility";
// Construct the GetSingleItem REST call
$apicall = "$URL?callname=GetSingleItem&version=$compatabilityLevel"
. "&appid=$appID&ItemID=$ItemID"
. "&responseencoding=XML"
. "&IncludeSelector=$includeSelector";
$xml = simplexml_load_file($apicall);
if ($xml) {
$json = json_encode($xml);
$array = json_decode($json,TRUE);
return $array;
}
return false;
}