1

我目前正在使用 YouTube 的 API JSON-C 响应从播放列表中提取数据并在列表中显示内容。我正在使用 PHP 执行此操作,但是因为 YouTube 限制了调用视频的最大数量,所以我遇到了一个绊脚石。我可以请求的最大值是 50,而我有超过 200 个视频需要放入列表中,并且我希望能够动态地执行此操作。

我知道我将不得不循环响应,这就是我所做的,但有没有办法可以动态完成?

如果你能帮助我,那就太好了,我的代码是:

$count = 0;
foreach($data->data->items as $item) {
    $count++;
    echo $count." ".$item->id;
    echo " - ";
    echo $item->title;
    echo "<br />";

    if($count == 50) {
        $query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=50&max-results=50&v=2&alt=jsonc";
        $data = file_get_contents($query);
        if($data){
            $data = json_decode($data);
            foreach($data->data->items as $item) {
                $count++;
                echo $count." ".$item->id;
                echo " - ";
                echo $item->title;
                echo "<br />";
            }
        }
    }

    if($count == 100) {
        $query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=100&max-results=50&v=2&alt=jsonc";
        $data = file_get_contents($query);
        if($data){
            $data = json_decode($data);
            foreach($data->data->items as $item) {
                $count++;
                echo $count." ".$item->id;
                echo " - ";
                echo $item->title;
            echo "<br />";
            }
        }
    }
}

等等...

如果你能帮助我,或者至少给我指出正确的方向,那就太好了,谢谢。

4

2 回答 2

0

一种方法是遍历请求,然后遍历请求中的每个项目。像这样:

$count = 1;
do {
    $data = ...; // get 50 results starting at $count
    foreach ($data->items as $item) {
        echo "$count {$item->id} - {$item->title}<br />\n";
        $count++;
    }
} while (count($data->items) == 50);

Note that start-index is 1-based, so you have to query for 1, 51, 101 etc.

(This is actually quite similar to reading a file through a buffer, except with a file you've reached the end if the read gives you 0 bytes, while here you've reached the end if you get less than the amount you asked for.)

于 2011-02-16T10:52:06.430 回答
0

What I would do is first call the 4 pages, and then combine the results into 1 single array, then iterate over the data.

$offsets = array(0,50,100,150);
$data = array();

foreach($offsets as $offset)
{
    $query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=" . $offset . "&max-results=50&v=2&alt=jsonc";
    $set = file_get_contents($query);
    if(!emprty($set ))
    {
        $data = array_merge($data,json_decode($set));
    }
}

//use $data here 
于 2011-02-16T11:03:20.183 回答