This question already has answers here:
How do I get video durations with YouTube API version 3?
(7 answers)
Closed 4 years ago.
I want to get the duration of a Youtube video. Here's the code I tried:
$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
Please check the XML file. I got the title of this video. I want to get duration from <yt:duration seconds='29'/>.
How to get the seconds attribute this <yt> tag?
Due to the upcoming deprecation of the YouTube v2 API, here is an updated solution.
Start by cloning the Google API PHP Client here
Next, you'll want to register an application with Google here by creating a new Project, turning on the YouTube Data API under the "APIs and auth → API" section, and
Create a new OAuth Client ID under "APIs and auth → Credentials" and add the full path to your redirect URI list. (i.e. http://example.com/get_youtube_duration.php)
Use this code (which was adapted from this sample code), while making sure to fill in the $OAUTH2_CLIENT_ID and $OAUTH2_CLIENT_SECRET variables with your own values from step 3.
Hardcode a value for the $videoId variable or set it using the video_id get parameter (i.e. http://example.com/get_youtube_duration.php?video_id=XXXXXXX)
Visit your script, click the link to authorize the app and use your google account to get a token, which redirects you back to your code and will display the duration.
Here is your output:
Video Duration
0 mins
29 secs
Some additional resources:
https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration
https://developers.google.com/youtube/v3/docs/videos/list
The following works for the V2 API only.
This worked for me based on the assumption that there is only one duration element in the feed.
<?php
$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');
print "TITLE: ".$title."<br />";
print "Duration: ".$duration ."<br />";
Output:
TITLE: Introducing iTime
Duration: 29
Here it is YouTube API V3, with example of getting video duration, but do not forget to create your API key at https://console.developers.google.com/project
$vidkey = "cHPMH2sa2Q" ; video key for example
$apikey = "xxxxxxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
A short and simple solution using SimpleXML:
function getYouTubeVideoDuration($id) {
$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/'.$id);
return strval($xml->xpath('//yt:duration[#seconds]')[0]->attributes()->seconds);
}
All the prev answers provide the duration in a text format:
This solution will give you the hours / minutes / seconds for you to transform to whatever format you would like:
function getDurationInSeconds($talkId){
$vidkey = $talkId;
$apikey = "xxxxx";
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
preg_match_all('/(\d+)/', $VidDuration, $parts);
$hours = intval(floor($parts[0][0]/60) * 60 * 60);
$minutes = intval($parts[0][0]%60 * 60);
$seconds = intval($parts[0][1]);
$totalSec = $hours + $minutes + $seconds; // This is the example in seconds
return $totalSec;
}
Very easy
function getYoutubeDuration($videoid) {
$xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
$result = $xml->xpath('//yt:duration[#seconds]');
$total_seconds = (int) $result[0]->attributes()->seconds;
return $total_seconds;
}
//now call this pretty function. As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
You can also get the duration in JSON
$video_id = "<VIDEO_ID>";
http://gdata.youtube.com/feeds/api/videos/$video_id?v=2&alt=jsonc
Oh! Sorry you can get it by:
$duration = $xml->getElementsByTagName('duration')->item(0)->getAttribute('seconds');
Related
This question already exists:
Instagram/Facebook deprecating many APIs [duplicate]
Closed 4 years ago.
After battling for many days to write a PHP script to access the feed data from selected public Facebook pages, I finally got the below code to work.
I deployed the script on my server and applied a cron to run it every hour or so for almost a month with no problems but yesterday suddenly it stopped working and now spits out the error:
Unsupported get request. Object with ID '483096775077541' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
What has changed, could someone please help?
<?php
$config['App_ID'] = 'xxxxxxxxx';
$config['App_Secret'] = 'ssssssssssssssssssss';
$token_url = "https://graph.facebook.com/oauth/access_token?"
."client_id=".$config['App_ID']
."&client_secret=".$config['App_Secret']
."&grant_type=client_credentials";
$grant = json_decode( file_get_contents($token_url) );
$page_i = 0;
$page_target = 1;
$graph_url = "https://graph.facebook.com/483096775077541/feed?access_token=".$grant->access_token;
while ($page_i < $page_target) :
$feedtext = file_get_contents($graph_url);
$feed = json_decode( str_replace('\n','<br />',$feedtext) );
foreach($feed->data as $data)
{
if( isset($data->message) ){
$lines = explode('<br />', $data->message);
echo '
<p>
<strong>'.$lines[0].'</strong>
<div>'.$data->message.'</div>';
echo '<div>'.$data->updated_time.'</div>
<div>'.$data->id.'</div>
</p>
';
}
}
$graph_url = $feed->paging->next;
$page_i++;
endwhile;
https://developers.facebook.com/blog/post/2018/04/04/facebook-api-platform-product-changes
As we begin enhancing our new app review process and make changes to our platform, the Events, Groups, Pages and Instagram APIs will no longer be available to new developers
Since this stopped working yesterday, it is definitely related to the recent changes. The only thing you can do is wait right now.
I'm doing what I would consider to be the most basic API call to the web-app at http://rolz.org/api/?4d20 using Pest PHP REST client. Using a Chrome plugin REST client, I get the expected results without an error:
result=45
details= [ 16 +20 +3 +6 ]
code=4d20
illustration=<span class="dc_dice_a">4</span><span class="dc_dice_d">D20</span>
timestamp=1370200094
However, using Pest PHP REST client, my results are prepended with an error message:
string $rolldice = result=Error: please check your formula (/52)
details=/ [ 9 +16 +20 +7 ]
code=/4d20
illustration=<span class="dc_operator">/</span><span class="dc_dice_a">4</span><span class="dc_dice_d">D20</span>
timestamp=1370200381
using this code:
include '../Pest.php';
function callDieRoller($num, $faces){
$result = array();
$curl = curl_init();
$url = 'http://rolz.org/api/?';
$pest = new Pest($url);
$rolldice = $pest->get($num.'d'.$faces);
$results = $rolldice;
return $results;
}
Why am I getting errors when making the API call with Pest?
It's because Pest ensures / between base api url and called url, so you are calling something like http://rolz.org/api/?/4d20. To make it work properly, you must define base url without question mark, and add it in front of every call:
$url = 'http://rolz.org/api/';
$pest = new Pest($url);
$rolldice = $pest->get('?'.$num.'d'.$faces);
$results = $rolldice;
I want to parse this URL with PHP to get the latitude of a specific address (2+bis+avenue+Foch75116+Paris+FR):
I use the google maps web service: http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
var_dump($obj);
It doesn't work. I have this error :
OVER_QUERY_LIMIT
So I searched on the web and I found that there is a limitation using google maps api (Min 1 sec between 2 queries and max 2500 queries per day)
Do you know any way to convert an adress to --> Latitude/Longitude ???
You are accessing results incorrectly.
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;
In youtube
How do i get the id of the latest uploaded video (the one that comes in the url like v=....) of a channel to which Im subscribed, for embeded
im using php in my server side
As of April 20, 2015, it looks like the answer mentioned above may no longer work. Here's an example using a YouTube Channel ID (can be found in the source of a Channel page.)
<?php
$id = NULL;
$channel_id = 'someChannelID';
$xml = simplexml_load_file(sprintf('https://www.youtube.com/feeds/videos.xml?channel_id=%s', $channel_id));
if (!empty($xml->entry[0]->children('yt', true)->videoId[0])){
$id = $xml->entry[0]->children('yt', true)->videoId[0];
}
echo $id; // Outputs the video ID.
Here's a example using the YouTube RSS feeds, simplexml_load_file, parse_url, and parse_str.
<?php
$id = NULL;
$username = 'YouTube';
$xml = simplexml_load_file(sprintf('http://gdata.youtube.com/feeds/base/users/%s/uploads?alt=rss&v=2&orderby=published', $username));
if ( ! empty($xml->channel->item[0]->link) )
{
parse_str(parse_url($xml->channel->item[0]->link, PHP_URL_QUERY), $url_query);
if ( ! empty($url_query['v']) )
$id = $url_query['v'];
}
echo $id; // Outputs the video ID.
Here's how to do it via the YouTube API once you set up your API Key.
<?php
$channel_id = 'someChannelId';
$api_key = 'yourAPIKey';
$json_url="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=".$channel_id."&key=".$api_key;
$json = file_get_contents($json_url);
$listFromYouTube=json_decode($json);
$id = $listFromYouTube->items[0]->snippet->resourceId->videoId;
echo $id; // Outputs the video ID.
Generating your API Key:
Goto - https://console.developers.google.com
Create a new project
Select "APIs & auth"
Select "APIs"
Select "Youtube Data API v3" and enable it
Select "Credentials"
Create new Key, select browser and then press create (don't enter
anything in the text box)
Same here as with Greg Brendel. YT did make some changes: "As we upgrade the YouTube Data API to bring more features, we’ll begin shutting down the old version on April 20, 2015. This will result in the current YouTube app not working on certain device models from 2012 and older."
https://support.google.com/youtube/answer/6098135?p=yt_devicesupport&hl=en&rd=1
Okay normally I'm all fine about the facebook API but I'm having a problem which just keeps me wondering. (I think it's a bug (Check ticket http://bugs.developers.facebook.net/show_bug.cgi?id=13694) but I wanted to throw it here if somebody has an idea).
I'm usng the facebook PHP library to count all attendees for a specific event
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending');
this works without a problem it correctly returns an array with all attendees...
now heres the problem:
This event has about 18.000 attendees right now.
The api call returns a max number of 992 attendees (and not 18000 as it should).
I tried
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending?limit=20000');
for testing but it doesn't change anything.
So my actual question is:
If I can't get it to work by using the graph api what would be a good alternative? (Parsing the html of the event page maybe?) Right now I'm changing the value by hand every few hours which is tedious and unnecessary.
Actually there are two parameters, limit and offset. I think that you will have to play with both and continue making calls until one returns less than the max. limit.
Something like this, but in a recursive approach (I'm writting pseudo-code):
offset = 0;
maxLimit = 992;
totalAttendees = count(result)
if (totalAttendees >= maxLimit)
{
// do your stuff with each attendee
offset += totalAttendees;
// make a new call with the updated offset
// and check again
}
I've searched a lot and this is how I fixed it:
The requested URL should look something like this.
Here is where you can test it and here is the code I used:
function events_get_facebook_data($event_id) {
if (!$event_id) {
return false;
}
$token = klicango_friends_facebook_token();
if ($token) {
$parameters['access_token'] = $token;
$parameters['fields']= 'attending_count,invited_count';
$graph_url = url('https://graph.facebook.com/v2.2/' . $event_id , array('absolute' => TRUE, 'query' => $parameters));
$graph_result = drupal_http_request($graph_url, array(), 'GET');
if(is_object($graph_result) && !empty($graph_result->data)) {
$data = json_decode($graph_result->data);
$going = $data->attending_count;
$invited = $data->invited_count;
return array('going' => $going, 'invited' => $invited);
}
return false;
}
return false;
}
Try
SELECT eid , attending_count, unsure_count,all_members_count FROM event WHERE eid ="event"