How to access youtube json date from the youtube google api? - php

How can I access thing like the url to a banner image, the channel title, the subscriber count, and the default logo image url from youtube google's api's for Youtube?
An example of the JSON api can be found here.
How can I access this contents using PHP?

proceed in this way:
$youtube = file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=snippet,brandingSettings&id=UCyoUx3RguJRgbaMo07yc_KA&key=AIzaSyCZonTWlCv92Nd93j5CuFFcqGciLIe5rx4");
$data = json_decode($youtube,true);
echo "BANNER IMAGE URL: ".$data['items'][0]['brandingSettings']['image']['bannerImageUrl']."<br>";
echo "CHANNEL TITLE: ".$data['items'][0]['brandingSettings']['channel']['title']."<br>";
and so on....
this tools its very good to view the structure of a json and extract what you need

This simple snippet should do the trick.
$myData = json_decode(file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=snippet,brandingSettings&id=UCyoUx3RguJRgbaMo07yc_KA&key=AIzaSyCZonTWlCv92Nd93j5CuFFcqGciLIe5rx4"));
var_dump($myData);
I would really recommend using cURL instead of file_get_contents() for performance reasons, however that should get you started.

Related

Google PHP Client for Blogger API v3, uploading images in posts

i'm working with Blogger API v3 using Google Client for PHP. Using the following code i'm able to post textual content, but i want to upload images as well, so how am i going to integrate images api to post?
$posts = $bloggerService->posts;
$NewPost = new Google_Service_Blogger_Post();
$NewPost->setTitle("Post Title ".time());
$NewPost->setLabels("Post Label1");
$NewPost->setContent("Post Content!!!!");
$NewPost->setCustomMetaData("Custom Meta Data ".time());
try
{
$nposts = $posts->insert("xx3606012xxx592612750xx",$NewPost);
}
catch(Exception $e)
{
print_r($e);
}
from the official api documentation i am unable to find / understand a way to attach images into posts.
https://developers.google.com/blogger/docs/3.0/reference/posts/insert
Edit-1:
one thought came into mind is that i can convert the images into base64 encoding and add it into post content, but that would make huge chunk of code depending on the size of the image and that might crash the browser!

Get Google drive video embed code using api

Hello everyone,
I was working on a project where i need to display a video specifically from my google drive on a webpage. I don't want to manually select the video and copy its embed code, is there a way we can obtain the embed code for a video using google api (PHP preferred) ?
So that i can use this code within an iframe and display the video.
Please also suggest if there are other ways.
Thanks in advance,
You can start with Google Drive API https://developers.google.com/drive/v3/web/quickstart/php and this segment of code i hope can help you.
<?php
// New Google Client, see all settings at link in description
$client = new Google_Client();
// New Google Drive Service
$service = new Google_Service_Drive($client);
// Params with filter of MIME type for search only videos mp4 (you can change this)
$optParams = [
'q' => "mimeType='video/mp4'",
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name, webViewLink)'
];
// Get files from our request
$files = $service->files->listFiles($optParams);
// Print an iframe for each video
foreach($files->files as $file){
// Now I need to make a little detail about the next lines of code so look at [Info]
$src = str_replace('/view', '/preview', $file->webViewLink);
echo '<iframe width="500" height="200" target="_parent" src="'. $src .'"></iframe>'
}
?>
[Info]
The objects returned from $service->files->listFiles($optParams) are Google_Service_Drive_DriveFile objects and each of these have a series of properties. From v3 of Google API a properties called embedLink was removed and there isn't an alternative for this property from v2(Migrate to Google Drive API v3) so as you seen in my code i use webViewLink property that return a URL to a view of file like this:
https://drive.google.com/file/d/123456789/view
But if you use this URL inside an <iframe> the browser notice to you an error:
Refused to display 'https://drive.google.com/file/d/123456789/view' in a frame because it set 'X-Frame-Options' to 'sameorigin'.`
I'm not holding you too much on this issue and there are a lot of question about this. So we need to request a preview of file and not a view an i do that with
str_replace('/view', '/preview', $file->webViewLink);
on the URL returned by the request. Now you can use this URL in a <iframe>

How to grab video snippets of youtube vids that contain a certain word

Ok, so based on this video; https://www.youtube.com/watch?v=7tjfeEAdY0I
I'm curious if it's possible to create a PHP script that will automatically grab all video's on a certain youtube channel (in this example; https://www.youtube.com/user/whitehouse/videos), grab all videos, check out the transcripts for a certain line or word, then save the vids with the correct timestamp, to make it possible to merge all these video's into one.
I know there's an API available to get all youtube video url's of a specific user, and you can get the transcripts per video, but scanning through all of them will be quite resource-heavy. I'm curious if you guys have any ideas on how to create such a script.
It is possible to capture all information related to videos of a particular YouTube channel using the YouTube V3 API.
The documentation of YouTube API can be found here
The related API functionality can be found here
The procedure to retrieve the transcript of a video from the json response from the API call will not be resource intensive and can be achieved in line of code as json parsing is a standard procedure and is supported on most of the languages including PHP.
Using the PHP wrapper, this can be achieved in a few lines of code.
Procedure:
Firstly, a request to listChannels under channels is send to receive all content details regarding a particular YouTube channel denoted by a channel ID. The related code snippet is:
$channelsResponse = $service->channels->listChannels('contentDetails', array('forUsername' => $channelId));
The second step is to parse through each video item which is done conveniently using a for loop like:
foreach ($channelsResponse['items'] as $channel) {}
The third step is to get the upload list id from the current item and send another request to the API with the parameter 'snippet'.
At this point, you will have all the content related data in json format and you need to parse and get the desired information.
The entire code snippet is :
$channelsResponse = $service->channels->listChannels('contentDetails', array('forUsername' => $channelId));
$data = [];
foreach ($channelsResponse['items'] as $channel)
{
$uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];
$playlistItemsResponse = $service->playlistItems->listPlaylistItems(
'snippet', array(
'playlistId' => $uploadsListId,
'maxResults' => 50
)
);
foreach ($playlistItemsResponse['items'] as $playlistItem)
{
$data[] = $playlistItem['snippet'];
}
}

How to get a Youtube channel RSS feed after 2015 April 20 (without v3 API)?

Now that API v2 is gone, what would be a way to get a simple RSS feed of a channel, without v3 API? I'm open to Yahoo Pipes or any workaround that is simpler than creating an application for v3 API if the target is a feed reader. I only need an RSS feed. It was available publicly until now and it can cease any minute now (I think). So why not let access to it without an API key anymore.
At RSS Reader section https://support.google.com/youtube/answer/6098135?hl=en there is an option to export to an OPML file your subscriptions. Then, looking at the contents of the OPML you can extract the feeds, and the structure of each feed is:
https://www.youtube.com/feeds/videos.xml?channel_id=XXXX
So you could generate new feeds from this structure if you know the channel id. This kind of feeds are not getting the "https://youtube.com/devicesupport" error, so I expect they are going to keep working.
You can get the feeds like this:
https://www.youtube.com/feeds/videos.xml?channel_id=CHANNELID
https://www.youtube.com/feeds/videos.xml?user=USERNAME
https://www.youtube.com/feeds/videos.xml?playlist_id=YOUR_YOUTUBE_PLAYLIST_NUMBER
But the JSON format which used to be supported (with additional parameter &alt=JSON) is not supported anymore.
Additionally you can request for API key for public access to your YouTube videos from your developer console and get YouTube Videos, Playlists in JSON format like this:
- Get Channels:
https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails&forUsername={YOUR_USER_NAME}&key={YOUR_API_KEY}
- Get Playlists:
https://www.googleapis.com/youtube/v3/playlists?part=snippet%2CcontentDetails&channelId={YOUR_CHANNEL_ID}&key={YOUR_API_KEY}
- Get Playlist Videos:
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails%2Cstatus&playlistId={YOUR_PLAYLIST_ID}&key={YOUR_API_KEY}
More information from YouTube v3 docs.
in you tube, click on the subscriptions on the left hand pane. This will open up all your subscriptions in the center of the page. Scroll down and you'll find a Export to RSS reader button which produces an xml file of all your subscriptions . I've done this and added it to my prefered rss reader feedly.
If you inspect any Youtube channel page, inside the <head> you will find an rss meta node like this:
<link rel="alternate"
type="application/rss+xml" title="RSS"
href="https://www.youtube.com/feeds/videos.xml?channel_id=UCn8zNIfYAQNdrFRrr8oibKw">
This should provide you with the data you need.
Get the channel id by searching for the attribute data-channel-external-id in the source code of the YouTube channel page. (thanks to helq).
This code will grab all video titles and ids from the feed and dump it into an array:
$channel_id = 'XXX'; // put the channel id here
$youtube = file_get_contents('https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id);
$xml = simplexml_load_string($youtube, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$youtube = json_decode($json, true);
$yt_vids = array();
$count = 0;
foreach ($youtube['entry'] as $k => $v) {
$yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['#attributes']['href']);
$yt_vids[$count]['title'] = $v['title'];
$count++;
}
print_r($yt_vids);
I've created a small PHP script that scrapes a Youtube URL for video links, and then outputs them as an atom feed: https://gist.github.com/Skalman/801436d9693ff03bc4ce
URLs such as https://www.youtube.com/user/scishow/videos work.
Caveats:
The tool doesn't scrape dates
Playlists won't include more than 100 videos
Playlists include the "play all" link
Author is correctly set only for channels (e.g. not playlists)
Maybe Youtube will block you if you use this too much (but hopefully the limits are high enough)
Likely several more...
There also exist RSS-Bridge witch can extract RSS feeds from a lot of services like Twitter, Google+, Flickr, Youtube, Identi.ca, etc.
source: https://github.com/sebsauvage/rss-bridge
demo server: https://bridge.suumitsu.eu/
try using this URL:
https://www.youtube.com/feeds/videos.xml?user=USERNAME
Works fine for me.
From My Blog Post: http://tcodesblog.blogspot.com/search/label/howtofindyouryoutubechannelfeed
HOW TO FIND YOUR YOUTUBE CHANNEL FEED
In the old days, it was easy (2009) but now a days it is much harder to find it (2012-present). Here is a quick way to find your new feed from your YouTube Channel. Remember to follow the list correctly!
First find your channel id: You can do this by going to your YouTube Channel in the Dashboard
Copy the channel id: Your channel id can be found when visiting your YouTube Channel from within the Dashboard
Copy your channel id: Copy your channel id and replace channelidgoeshere below with your channel id: https://www.youtube.com/feeds/videos.xml?channel_id=channelidgoeshere
Copy your entire YouTube Channel Feed and create a simplified feed: You can do this by creating a shorter feed link in FeedBurner at http://www.feedburner.com/ (Requires a Google account. Free to use.), which is also part of Google. Create a new feed (select I'm A Podcaster! to see your videos appear in the feed and to make your feed compatible with other feed readers such as: Digg Reader, Apple iPhone Apple News App, Apple iPhone Podcasts App, Feedly, etc.) -OR- edit an existing one by copying your entire YouTube Channel Feed and then click Save Feed Details as normal
Your YouTube Channel Feed now works and your videos can be seen in a feed file directly on your FeedBurner feed. Mine is at YouTube as a feed at https://www.youtube.com/feeds/videos.xml?channel_id=UCvFR6YxwnYfLt_QqRFk_r3g & at FeedBurner as http://feeds.feedburner.com/youtube/warrenwoodhouse with my videos that appear only as text format, as an example, since I need to update mine to show my videos. You can change different settings in FeedBurner and do other things so it's worth a try since it's free and easy to use. I highly recommend using FeedBurner or another feed creation service, however, FeedBurner is your best bet since it also includes cross-feed subscription service mechanism (USM - Universal Subscription Mechanism), which means your feed can be read from any compatible device such as a computer, mobile phone (with the correct app installed), via an older web browser (such as Internet Explorer which supports Web Slices & RSS/Atom/XML Feeds).
Your feed can also be opened up in Apple iPhone Apple News App & Apple iPhone Podcasts App on your Apple iPhone, Apple iPod Touch and Apple iPad if you've set the settings correctly to USM (Universal Subscription Mechanism). Once this is in effect, your feed can be viewed through different services and devices.
Your feed on FeedBurner allows you to create an Email Subscription, Headline Animator (which shows you how a link to the latest post) along with how many subscribers, Chiclets and other cool stuff.
I hope this answer proves useful and if you want to see some more cool awesome coding practices by me, please feel free to check out my T-Codes website at http://warrenwoodhouse.webs.com/codes for lots more stuff.
I have created an example Yahoo Pipes here.
http://pipes.yahoo.com/pipes/pipe.info?_id=6eeff0110a81f2ab94e8472620770b11
You can run this pipe by pressing "Run Pipe" without API Key filled. But you must provide your own API Key and channel id (which can be obtained via channels API) when cloned. Wanted to automate fetching channelId by YouTube username but not easy to pipe.
I've made a batch script that creates an RSS feed of your new subscription videos. You don't need an API key. The script uses 2 external tools: YouTube-DL and Xidel.
Anyway, read the following thread, and go to post 98 to download the script:
http://code.google.com/p/gdata-issues/issues/detail?id=3946#c98
I hope someone codes this to php, python, javascript, powershell or bash.
I think there are some changes in youtube response so i make some changes to get channel id from rss feed using Curl.
$channel_id = 'XXXXXXXX'; // put the channel id here
//using curl
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
$response=simplexml_load_string($response);
$json = json_encode($response);
$youtube= json_decode($json, true);
$count = 0;
if(isset($youtube['entry']['0']) && $youtube['entry']['0']!=array())
{
foreach ($youtube['entry'] as $k => $v) {
$yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['#attributes']['href']);
$yt_vids[$count]['title'] = $v['title'];
$count++;
}
}
else
{
$yt_vids[$count]['id']=str_replace('http://www.youtube.com/watch?v=', '', $youtube['entry']['link']['#attributes']['href']);
$yt_vids[$count]['title']=$youtube['title'];
}
echo "<pre>";
print_r($yt_vids);
I used the below code to integrate Youtube Feed with wordpress custom field "ACF plugin" & FancyBox
<?php
$channel_id = get_field('youtube_chanel_id'); //ACF text field
if ($channel_id){ // if channel_id not empty -- START
$youtube = file_get_contents('https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id);
$xml = simplexml_load_string($youtube, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$youtube = json_decode($json, true);
echo'<div class="col-md-12 youtube-videos-feed">';
foreach ($youtube['entry'] as $k => $v) {
$id = str_replace(array("yt:video:"), "", $v['id']); // Remove "yt:video:" from ID value
//$date = $v['updated']; // video updated date (disabled for now)
$title = $v['title']; // video title
echo '<a class="with-video" href="https://www.youtube.com/watch?v=',$id,'&autoplay=1&rel=0&controls=0&showinfo=0&modestbranding=0" data-fancybox="videos" data-caption="',$title,'" title="',$title,'" >
<div class="col-md-3 main-image post-image img-fancy">
<img src="https://img.youtube.com/vi/',$id,'/0.jpg" alt="',$title,'" >
</div>
</a>';
}
echo'</div>';
} // if channel_id not empty -- END
?>
I found a Chrome extension named Youtube RSS-ify that injects an RSS icon on video, channel and navigation pages. It was just what I was looking for.
Icons look like this:
I would suggest using an excellent rss parser. Many of them are available, but you can try http://simplepie.org/, one of the best I used for my personal projects.
Its pretty well documented with some examples.
Usage example
Note:Used YouTube channel college humor, you can get it from the channel page itself
<?php
include_once('../autoloader.php');
// Parse it
$feed = new SimplePie();
$feed->set_feed_url('https://www.youtube.com/feeds/videos.xml?channel_id=UCPDXXXJj9nax0fr0Wfc048g');
$feed->enable_cache(false);
$feed->init();
$items = $feed->get_items();
foreach ($items as $item)
{
echo $item->get_title() . "\n";
}
var_dump($feed->get_item_quantity());
Easiest way to get the channel id:
Open Subscription Manager (left panel, down below subscriptions) and click on the desired user.
The url will be in the form:
https://www.youtube.com/channel/XXXXXXXXXXXXXXXXX
So the feed url should be:
https://www.youtube.com/feeds/videos.xml?channel_id=XXXXXXXXXXXXXXXXX
Note: Better use channel ids rather than user names because user names may change.

Get youtube channel ID from website

I have the below code for retrieving views and subscribers from a YouTube channel "?q=dsagov"
$UserID = $_GET['q'];
$data = file_get_contents('http://gdata.youtube.com/feeds/api/users/'. $UserID.'');
$xml = new SimpleXMLElement($data);
$stats_data = (array)$xml->children('yt', true)->statistics->attributes();
$stats_data = $stats_data['#attributes'];
echo 'Views = '.$stats_data['subscriberCount'].'<br />';
echo 'Subscribers = '.$stats_data['totalUploadViews'].'<br />';
I would like to take this one step further and find the YouTube channel ID based on a website address, in this case https://www.gov.uk/government/organisations/driving-standards-agency .
So either REGEX the website find the Channel ID or another method which I am not aware of using YouTube API, I can put the URL of the website and have it find the official channel is this possible?
Thanks in advance.
Just to clarify
For example I would like to enter a URL in query "/?q=gov.uk/government/organisations/driving-standards-agency" what the script would do is find the YouTube Channel ID on the URL and run the API and display the results
I don't think this is possible.
Where would you search for website name ? This could be in user's descriptions, video descriptions, many more places for many users and videos.

Categories