Youtube API - Get duration of videos from a playlist - php

I need to get the duration of all the videos in a Youtube playlist.
I know that the API does not show me the duration of each video when doing the search of all, but it does show it if the query is made for a particular video.
Through PHP I tried to collect all the IDs from the playlist and then analyze each ID to get the data from the videos, but the script is too slow, although it should be stressed that it works well, is there any way to optimize it?...
function youtube_automusic($listas, $api_key, $resultados){
$nresultados = $resultados;
$lista_reproduccion_random = $listas;
$lista_reproduccion = $lista_reproduccion_random[array_rand($lista_reproduccion_random)];
$url_playlist = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&fields=items(snippet(resourceId(videoId)))&type=video&videoCategoryId=10&maxResults=".$nresultados."&playlistId=".$lista_reproduccion."&key=".$api_key;
$data = dlPage($url_playlist);
$data_decode = json_decode($data, true);
$number_song = 1;
$respuesta = array();
foreach ($data_decode as $items){
foreach ($items as $item){
$lista_ids =$item['snippet']['resourceId']['videoId'];
$url_video = "https://www.googleapis.com/youtube/v3/videos?id=".$lista_ids."&part=snippet,contentDetails&fields=items(etag,id,snippet(publishedAt,title,thumbnails(default(url)),tags),contentDetails(duration))&key=".$api_key;
$data_video = dlPage($url_video);
$data_video_decode = json_decode($data_video, true);
foreach ($data_video_decode as $items_videos){
foreach ($items_videos as $item_video){
$data_final = array(
'etag' => $item_video['etag'],
'idvideo' => $item_video['id'],
'titulovideo' => $item_video['snippet']['title'],
'thumbnail' => $item_video['snippet']['thumbnails']['default']['url'],
'duracion' => $item_video['contentDetails']['duration'],
'videoplay' => $number_song++
);
array_push($respuesta, $data_final);
}
}
}
}
return json_encode($respuesta);
}

With your code on a 50 item playlist it would take 51 API calls.
Instead of doing a single videos request for each video in the playlist, get all the video IDs in the playlist first and then make videos requests for up to 50 at a time (the ID parameter takes a comma-separated list of up to 50 items).
Then a 50 item playlist would only take 2 API calls.
Should be much faster.

I just ran a test here
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails&id=Ks-_Mh1QhMc&fields=items(etag%2Cid%2Csnippet(publishedAt%2Ctitle%2Cthumbnails(default(url))%2Ctags)%2CcontentDetails(duration))&key={YOUR_API_KEY}
Results:
{
"items": [
{
"etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/aCBUdsaX0W34z3It8a8FCh5uteo\"",
"id": "Ks-_Mh1QhMc",
"snippet": {
"publishedAt": "2012-10-01T15:27:35.000Z",
"title": "Your body language may shape who you are | Amy Cuddy",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/default.jpg"
}
},
"tags": [
"Amy Cuddy",
"TED",
"TEDTalk",
"TEDTalks",
"TED Talk",
"TED Talks",
"TEDGlobal",
"brain",
"business",
"psychology",
"self",
"success"
]
},
"contentDetails": {
"duration": "PT21M3S"
}
}
]
}
I suggest that you run the same request using the Google APIs Explorer using the video id that you are having an issue with to verify that its not an issue with the API not returning your duration.

Related

Wordpress Shortcode to get Youtube Channel Views via YouTube API

I am Wordpress User and not the Programmer.
I want to create a shortcode in the functions.php to get the total views of any youtube channel.
I use the shortcode and give the channel ID Value. After the shortcode function gives back via YouTube API the current Channel Views of the given Channel ID.
In the YouTube Documentation, I found the following Code:
function channelsListById($service, $part, $params) {
$params = array_filter($params);
$response = $service->channels->listChannels(
$part,
$params
);
print_r($response);
}
channelsListById($service,
'statistics',
array('id' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw'));
}
The Response looks like that:
/**
* API response
*/
{
"kind": "youtube#channelListResponse",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/d9WwK8U1FuV6c-shZpzmnYUgGvQ\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/Psv3E9LCdk66gkF4HSIYK44crMI\"",
"id": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"statistics": {
"viewCount": "118283693",
"commentCount": "393",
"subscriberCount": "1165598",
"hiddenSubscriberCount": false,
"videoCount": "4435"
}
}
]
}
I think, I need to add some code to get the item field "viewCount" Value.
I don´t know if it is possible to do that, but I hope some of you Pros know the solution.
At the End of the Code, I just have to add:
add_shortcode( 'channel_views', 'shortcode_title' );
Would be amazing, if you could respond with the code I have to invert to the functions.php ;)
If you need more information to be able to respond, just ask me.
Use this plugin.
https://wordpress.org/plugins/youmax-channel-embeds-for-youtube-businesses/
This plugin simply gets all the videos from youtube channel in the grid format.

How to get other pages followers count number in Instagram?

is there possibility to get other pages follower count number in Instagram?
I can get only my profile followers count number, but I want to get other followers too? (for example in php)
Any ideas?
Yes, it's possible with ?__a=1 queries which return json.
$otherPage = 'nasa';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
if ($data !== null) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo $follows . ' and ' . $followedBy;
}
}
Jumping through hoops to get an app approved for quickly checking follower counts seemed excessive so I had a look at network requests on Instagram's web search and saw that typing in the search box fires off requests to this URL:
https://www.instagram.com/web/search/topsearch/?query={searchquery}
That returns a JSON feed which has a bunch of info on the user including a value for follower_count. If you are logged in, the results are weighted by relevance to your account, but you don't have to be authenticated or even logged in to get a result:
{
"has_more": false,
"status": "ok",
"hashtags": [],
"users": [
{
"position": 0,
"user": {
"username": "thenativepaul",
"has_anonymous_profile_picture": false,
"byline": "457 followers",
"mutual_followers_count": 0.0,
"profile_pic_url": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-19/11373838_482400848607323_1803683048_a.jpg",
"full_name": "Paul Almeida-Seele",
"follower_count": 457,
"pk": 21072296,
"is_verified": false,
"is_private": false
}
},
{
"position": 1,
"user": {
"username": "the_native_warrior",
"has_anonymous_profile_picture": false,
"byline": "251 followers",
"mutual_followers_count": 0.0,
"profile_pic_url": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-19/s150x150/14473927_312669442422199_4605888521247391744_a.jpg",
"profile_pic_id": "1352745514521408299_1824600282",
"full_name": "Paul Carpenter",
"follower_count": 251,
"pk": 1824600282,
"is_verified": false,
"is_private": true
}
}
],
"places": [ ]
}
Using yahoo query language
https://query.yahooapis.com/v1/public/yql?q=select * from html where url='https://www.instagram.com/USERNAME/' and xpath='/html/body/script[1]'&format=json
you can get any user's followers count but you cant get the user's followers details, you can only get your follower list.
This is API to get follower count of any user:
https://api.instagram.com/v1/users/{user-id}/?access_token=ACCESS-TOKEN
https://www.instagram.com/developer/endpoints/users/#get_users
UPDATE: I noticed that didn't work and I just tried this: https://api.instagram.com/v1/users/self/?access_token=XXXXX and got some good info ... MQ
There are a few analytics tools that allow you to get the follower count without an access token other than your own. If you login to Crowdbabble and add an Instagram account, you will be asked to login to your Instagram account. After that, though, you can add any Instagram account and get the number of followers. This will give you the follower list, most engaging followers, and most influential followers for any account.
If you apply for the Instagram API (now requires a written application and a video submission), you can set up an app like this yourself. You can make calls to different accounts using just one access token.
I've used yahoo API, in my case I figured out like this,
hope this helps someone because I've searched a lot for this.
$url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url=%27https://www.instagram.com/USERNAME/%27%20and%20xpath=%27/html/body/script[1]%27&format=json";
$json = file_get_contents($url);
$obj = json_decode($json, true);
$content = $obj['query']['results']['script']['content'];
$content = str_replace("window._sharedData =", "", $content);
$content = str_replace(";", "", $content);
$content = trim($content);
$json = json_decode($content);
$instagram_follower_count = $json->entry_data->ProfilePage{0}->user->followed_by->count;
anyone know better way get directly with JSON object, without replacing special characters ? please correct me if yes.

YouTube API v3 get latest video uploads for a username with PHP

I am trying to get a list of a user's latest videos/uploads. I am trying to get my head around this new v3 API, but I cannot find any properly working PHP code examples, not even on the dedicated YouTube API website.
I have a list of YouTube usernames, and I just want to simply get a list of their latest videos with video ID, title, thumbnail URL, etc. Basically in a foreach loop.
Any advice?
I have the following code, I need to make it work by the actual YouTube usernames.
$url = 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=ferrariworld&key=ZZZZZZZZ';
$json = json_decode(file_get_contents($url), true);
foreach ($json as $item){
echo $item[0]['id'];
echo $item[0]['title'];
}
Use the channels endpoint with a forUsername attribute (see the documentation for the endpoint).
GET https://www.googleapis.com/youtube/v3/channels?part=id&forUsername={USERNAME}&key={YOUR_API_KEY}
It will give you this kind of response:
{
"kind": "youtube#channelListResponse",
"etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/7Q8DJLb6b2hwYAXUQLI3ftt3R8U\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/pDjr9xPn51KtRM3gbMOq2aHBIbY\"",
"id": "UCr3LuetcEeidWiuhxaw4B2g"
}
]
}
The channel ID of that user can be found at items[0]['id'] if you convert the JSON to array.
As for your edit, you’re accessing the JSON object incorrectly. You need to use something like this.
if (array_key_exists('items', $json) && count($json['items']) === 1) {
$item = $json['items'][0];
$channelId = $item['id']; // The users channel ID.
}

Looking for effiicient way to pull data from facebook graph api

I've been recently working with facebook graph api , when I'm pulling user's recents status messages using https://graph.facebook.com/me/statuses?access_token=... all I get is a long list which contains details about the status content, and I want to pull the names of people who liked the status.
The current solution I've been thinking about is using preg match,
I'd like to know if you guys have any other suggestions,
Thanks in advance
I'm not sure what path you're using, but you can fetch the list of users who like a particular status update by requesting the likes connection on an update.
For example, requesting https://graph.facebook.com/10150710880081168/likes yields something like the following for me:
{
"data": [
{
"id": "276700623",
"name": "Vikki Carter"
},
{
"id": "1514365200",
"name": "Darren Bean"
},
{
"id": "539760281",
"name": "Ian Sidaway"
}
],
"paging": {
"next": "https://graph.facebook.com/10150710880081168/likes?format=json&limit=25&offset=25&__after_id=539760281"
}
}
You'll need the ID of the status update, but also the user_status permission from the logged-in user.
EDIT: Iterating over the returned data and assigned users into an array:
<?php
$result = $facebook->api('[status_id]/likes');
$names = array();
foreach ($result['data'] as $user) {
$names[] = $user['name'];
}
You should now have an array of names of users who liked the status in question.

How to use Facebook graph API to retrieve fan photos uploaded to wall of fan page?

I am creating an external photo gallery using PHP and the Facebook graph API. It pulls thumbnails as well as the large image from albums on our Facebook Fan Page.
Everything works perfect, except I'm only able to retrieve photos that an ADMIN posts to our page. (graph.facebook.com/myalbumid/photos) Is there a way to use graph api to load publicy uploaded photos from fans?
I want to retrieve the pictures from the "Photos from" album, but trying to get the ID for the graph query is not like other albums... it looks like this: http://www.facebook.com/media/set/?set=o.116860675007039
Another note: The only way i've come close to retreiving this data is by using the "feed" option.. ie: graph.facebook.com/pageid/feed
EDIT:
This is about as far as I could get- it works, but has certain issues stated below. Maybe someone could expand on this, or provide a better solution. (Using FB PHP SDK)
<?php
require_once ('config.php');
// get all photos for album
$photos = $facebook->api("/YourID/tagged");
$maxitem =10;
$count = 0;
foreach($photos['data'] as $photo) {
if ($photo['type'] == "photo"):
echo "<img src='{$photo['picture']}' />", "<br />";
endif;
$count+= 1;
if ($count >= "$maxitem") break;
}
?>
Issues with this:
1) The fact that I don't know a method for graph querying specific "types" of Tags, I had to run a conditional statement to display photos.
2) You cannot effectively use the "?limit=#" with this, because as I said the "tagged" query contains all types (photo, video, and status). So if you are going for a photo gallery and wish to avoid running an entire query by using ?limit, you will lose images.
3) The only content that shows up in the "tagged" query is from people that are not Admins of the page. This isn't the end of the world, but I don't understand why Facebook wouldn't allow yourself to be shown in this data as long as you posted it "as yourself" and not as the page.
You need to retrieve all the albums and then get all the photos. This can be easily done by using FQL:
SELECT pid,owner,src_small,src_big
FROM photo
WHERE aid IN (
SELECT aid
FROM album
WHERE owner = your_page_id
)
EDIT:
Also you need to query the stream table to get the wall posts then check if you have attachments and the type of the attachment:
SELECT attachment
FROM stream
WHERE source_id = 116860675007039
Result:
[
{
"attachment": {
"media": [
{
"href": "http://www.facebook.com/photo.php?fbid=1801693052786&set=o.116860675007039",
"alt": "test",
"type": "photo",
"src": "http://photos-f.ak.fbcdn.net/hphotos-ak-snc6/185861_1801693052786_1553635161_1863491_4978966_s.jpg",
"photo": {
"aid": "6672812206410774346",
"pid": "6672812206412558147",
"fbid": 1801693052786,
"owner": 1553635161,
"index": 11,
"width": 246,
"height": 198
}
}
],
"name": "",
"caption": "",
"description": "",
"properties": [],
"icon": "http://b.static.ak.fbcdn.net/rsrc.php/v1/yz/r/StEh3RhPvjk.gif",
"fb_object_type": "photo",
"fb_object_id": "6672812206412558147"
}
},
{
"attachment": {
"description": ""
}
},
...etc
]
try this FQL:
SELECT message,attachment,comments
FROM stream
WHERE source_id=YOUR_PAGE_ID AND filter_key="others" AND type=""
filter_key="others" - this will filter posts from everyone else, but not from Admin
type="" - this will filter out comments, so will leave you with photos (maybe videos and other strenge things, but removing text posts will reduce result massively)

Categories