How to list more than 50 Youtube videos using cURL

8

I need to return all videos from a certain youtube user, but my current function only returns 50, which is the maximum allowed by the API. is there any method to do this?

$cURL = curl_init(sprintf('http://gdata.youtube.com/feeds/api/users/%s/uploads?start-index=1&max-results=50&orderby=published', 'nerineitzke'));
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_FOLLOWLOCATION, true);
$return = curl_exec($cURL);
curl_close($cURL);
$xml = new SimpleXMLElement($return);

$i = 0;
foreach($xml->entry AS $video):
    $titulo = (string)$video->title;
    echo "$titulo <br/><br/>";
    $i++;
endforeach;

echo $i; // i = 50
    
asked by anonymous 04.04.2014 / 14:52

2 answers

7

In the URL there is the start-index parameter. If it has a value of 1, the results from 1 to 50 will be brought in. If it has a value of 2, the results from 2 to 51 will be brought in. And so on.

You can make a loop that changes the value of start-index , similar to what you already did in sprintf (by putting a %s ), and rotate queries from 50 to 50:

  • First iteration (1-50): start-index=1
  • Second iteration (50-100): start-index=50
  • ...

To find out if there are more pages available, you can look for the <link rel="next" /> parameter within the XML. If it does, it means there is one more page with results, and you can continue the loop.

Start-index documentation
Documentation of totalResults and link next

    
04.04.2014 / 15:34
2

You can use JSON to get the values more easily, just put the alt = jsonc parameter in the url.

Example:

$json_url = file_get_contents('http://gdata.youtube.com/feeds/api/users/nerineitzke/uploads?v=2&alt=jsonc&start-index=1&max-results=50&orderby=published');

$json = json_decode($json_url);

$totalItens = $json->data->totalItems; // Mostra o total de itens cadastrados.

$videos = $json->data->items;

$i = 1;
foreach($videos as $video){ 
    echo $i . ' - ' . $video->title . '<br>';
    $i++;
}
    
04.04.2014 / 17:02