我正在尝试获取几乎已存档的 channel 视频,但是 YouTube 每页检索 50 个结果,而我的 channel 有 150 个视频,对结果进行分页会更整洁。是否可以使用以下代码执行此操作?如果是这样,请告诉我怎么做
我是一名 PHP 程序员,但对使用它和向您发送 http 请求(包括分页)完全陌生。
这是我目前所拥有的
<?php
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/users/gamertv273/uploads?start-index=1&max-results=10';
$sxml = simplexml_load_file($feedURL);
$i=0;
foreach ($sxml->entry as $entry) {
$media = $entry->children('media', true);
$watch = (string)$media->group->player->attributes()->url;
$thumbnail = (string)$media->group->thumbnail[0]->attributes()->url;
?>
<link rel='previous' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/api/users/gamertv273/uploads?start-index=1&max-results=10'/>
<link rel='next' type='application/atom+xml'
href='http://gdata.youtube.com/feeds/api/users/gamertv273/uploads?start-index=2&max-results=10'/>
<div class="videoitem">
<div class="videothumb"><a href="<?php echo $watch; ?>" class="watchvideo"><img src="<?php echo $thumbnail;?>"
alt="<?php echo $media->group->title; ?>" /></a></div>
<div class="videotitle">
<h3><a href="<?php echo $watch; ?>" class="watchvideo"><?php echo $media->group->title; ?></a></h3>
</div>
</div>
<?php $i++; if($i==3) { echo '<div class="clear small_v_margin"></div>'; $i=0; } } ?>
最佳答案
http://gdata.youtube.com/feeds/api/users/gamertv273/uploads?start-index=100&max-results=50
start-index 是开始的视频索引。
max-results 是返回的条目数(允许的最大值为 50)。
第一步
首先,我建议您将页码 解析到您自己的页面中,然后您的代码相应地查询YTube。即
www.yourwebsite.com/your-page.php?page=1
在你的代码中:
<?php
$results_per_page = 20;
$start_index = $_GET['page'] - 1 * ($results_per_page + 1);
$feedURL = 'http://gdata.youtube.com/feeds/api/users/gamertv273/uploads?start-index=' . $start_index . '&max-results=' . $results_per_page;
//[rest of the code]
?>
如果您的页面是 1,这将返回结果 0-20,如果您的页面是 2,则返回 20-40,等等。
第 2 步
然后,您需要输入页码。如果您有 126 个视频,那么应该有 7 个页面可用,每个页面有 20 个结果。要了解总共有多少个视频,请引用以下 API:
http://gdata.youtube.com/feeds/api/users/gamertv273/uploads?v=2&alt=jsonc&max-results=0
您现在可以使用 json_decode() 解析 json 响应,获取 totalItems 并除以 $results_per_page 以获得可用页面数。然后,使用上一个/下一个按钮轻松打印每个页面的标签。
<a href="www.yourwebsite.com/your-page.php?page=1">previous page</a>
<a href="www.yourwebsite.com/your-page.php?page=3">next page</a>
<a href="www.yourwebsite.com/your-page.php?page=1">page 1</a>
<a href="www.yourwebsite.com/your-page.php?page=2">page 2</a>
<a href="www.yourwebsite.com/your-page.php?page=3">page 3</a>
<a href="www.yourwebsite.com/your-page.php?page=4">page 4</a>
关于php - 如何以分页方式从 YouTube 获取用户视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25138335/