Search code examples
zend-frameworkyoutube-apizend-gdata

Youtube API - How to limit results for pagination?


I want to grab a user's uploads (ie: BBC) and limit the output to 10 per page.

Whilst I can use the following URL: http://gdata.youtube.com/feeds/api/users/bbc/uploads/?start-index=1&max-results=10

The above works okay.

I want to use the query method instead:

The Zend Framework docs: http://framework.zend.com/manual/en/zend.gdata.youtube.html

State that I can retrieve videos uploaded by a user, but ideally I want to use the query method to limit the results for a pagination.

The query method is on the Zend framework docs (same page as before under the title 'Searching for videos by metadata') and is similar to this:


$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setTime('today');
$query->setMaxResults(10);
$videoFeed = $yt->getUserUploads( NULL, $query );

print '<ol>'; foreach($videoFeed as $video): print '<li>' . $video->title . '</li>'; endforeach; print '</ol>';

The problem is I can't do $query->setUser('bbc').

I tried setAuthor but this returns a totally different result.

Ideally, I want to use the query method to grab the results in a paginated fashion.

How do I use the $query method to set my limits for pagination?

Thanks.


Solution

  • I basically solved this in the same way as worchyld with a slight twist:

        $username = 'ignite';
        $limit = 30;  // Youtube will throw an exception if > 50
        $offset = 1;  // First video is 1 (silly non-programmers!)
        $videoFeed = null;
        $uploadCount = 0;
        try {
            $yt = new Zend_Gdata_YouTube();
            $yt->setMajorProtocolVersion(2);
            $userProfile = $yt->getUserProfile($username);
            $uploadCount = $userProfile->getFeedLink('http://gdata.youtube.com/schemas/2007#user.uploads')->countHint;
    
            // The following code is a dirty hack to get pagination with the YouTube API without always starting from the first result
            // The following code snippet was copied from Zend_Gdata_YouTube->getUserUploads();
            $url = Zend_Gdata_YouTube::USER_URI .'/'. $username .'/'. Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX;
            $location = new Zend_Gdata_YouTube_VideoQuery($url);
            $location->setStartIndex($offset);
            $location->setMaxResults($limit);
            $videoFeed = $yt->getVideoFeed($location);
        } catch (Exception $e) {
            // Exception handling goes here!
            return;
        }
    

    The Zend YouTube API seems silly as the included getUserUploads method never returns the VideoQuery instance before it actually fetches the feed, and while you can pass a location object as a second parameter, it's an "either-or" situation - it'll only use the username parameter to construct a basic uri or only use the location, where you have to construct the whole thing yourself (as above).