陷入了对youtube api播放列表结果进行分页的困境,试图计算播放列表中所有视频的总持续时间



我想为我的drupal网站制作一个小php片段,它统计youtube播放列表中所有视频的所有持续时间。我设法在这个网站上找到了一个很好的起点,我做了一些改变,它几乎很好:

<?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 ;
?>

我的问题是,我不能分页,youtube最多只能给我50个结果。我尝试使用起始索引参数,但对我不起作用。我在youtube的api页面上搜索,但我不知道该怎么做。我不是程序员,这是我用有限的编程知识所能想到的。要计算播放列表中的所有视频,我应该在代码中添加什么?或者,如果有人能帮我做另一个片段,那也太完美了。

谢谢!

很抱歉不能在这里测试,但考虑到您遇到的错误,我认为您首先需要检查从youtube收到的数据。

我还为您提供了一种友好的方式来测试当前页面和每页的请求。

<?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."
}
?>

相关内容

最新更新