Stuck with paginating youtube api playlist results

2019-08-10 07:20发布

问题:

I would like to make a little php snippet for my drupal site, which counts all the durations of all the videos in a youtube playlist. I managed to find a good starting point here at this site, I made some changes, and it is almost good:

<?php
$playlist_id = "266DBEDBE6892C11";
$url = "https://gdata.youtube.com/feeds/api/playlists/".$playlist_id."?v=2&alt=json&start-index=1&max-results=50";
$data = json_decode(file_get_contents($url),true);
$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);
$length = 0;

echo "Playlist Name: ".$info["title"]['$t'].'<br/>';
echo "Number of Videos (".$nVideo."):<br/>";
for($i=0;$i<200;$i++){
$temporary_length =  $video[$i]['media$group']['yt$duration']['seconds'];
$length += $temporary_length;
echo "Lenght: ". $temporary_length ."<br/>";
}

echo "Length: " . $length ;

?>

My problem is, that I can't paginate, youtube only gives me maximum 50 results. I tried with the start-index parameter, but that did not work for me. I search through the youtube api pages, but I have no clue hot to do it. I am no programmer, this is what I could come up with with my limited programming knowledge. What should I add to the code, to count all the videos in a playlist? Or If someone could help me with another snippet, that would be perfect also.

Thank you!

回答1:

Sorry can't test this here, but taking into account what error you are getting I think you first need to check what data you have receieved back from youtube.

I also put in a friendly way for you to test the current page and requests per page.

<?php

//Configurable
$playlist_id = "266DBEDBE6892C11";
$results_per_request = 50;
$current_page = 1;

$start_index = $request_per_page * ($current_page - 1) + (($current_page > 1) ? 1 : 0);
$url = "https://gdata.youtube.com/feeds/api/playlists/".$playlist_id."?v=2&alt=json&start-index=".$start_index."&max-results=".$results_per_request;
$data = json_decode(file_get_contents($url),true);

if (is_array($data) && count($data) > 0)
{
$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);
$length = 0;

echo "Playlist Name: ".$info["title"]['$t'].'<br/>';
echo "Number of Videos (".$nVideo."):<br/>";
for($i=0;$i<200;$i++){
$temporary_length =  $video[$i]['media$group']['yt$duration']['seconds'];
$length += $temporary_length;
echo "Lenght: ". $temporary_length ."<br/>";
}

echo "Length: " . $length ;
}
else
{
echo "Youtube did not return any more results."
}

?>