How to list more than 50 Youtube videos using Curl

Asked

Viewed 1,210 times

9

I’m needing to return all videos from a particular youtube user, but my current function only returns 50, which is the maximum allowed by the API. there is some method of doing 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

2 answers

8


In the URL there is the parameter start-index. If the value is 1, the results will be brought from 1 to 50. If the value is 2, the results will be brought from 2 to 51. And so on and so forth.

You can make a loop that changes the value of the start-index, similar to what you’ve done in sprintf (putting a %s), and rotate the queries every 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 search by the parameter <link rel="next" /> within XML. If it exists, it is a sign that there is one more page with results, and you can continue the loop.

Documentation of the start-index
Documentation of totalResults and link next

  • Yeah, I thought that too, but the problem is that there’s no return on the maximum number of videos, so how would you identify that the next loop contains videos, and whether it contains 50 or less?

  • 4

    At the beginning of XML has a tag that says the total of results. Here: <openSearch:totalResults>1128</openSearch:totalResults>. You can base yourself on this value to make the calculation.

  • In any case, I recommend that you read in the documentation the part about "Pagination and total result Counts". The API does not guarantee that this number is accurate. In addition, there is a fixed limitation to the maximum number of videos that can be loaded (even paging).

  • 2

    Ah, now I found out: there is a parameter in XML called <link rel="next" />. If it is present, it is a sign that there is another page. If it is not, you can stop the loop. Hugs

3

You can use JSON to pick up the values more easily, just put the parameter alt=jsonc at 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++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.