Looping code using PHP
I am currently using YouTube's API JSON-C response to pull data from a playlist and display the content in a list. I am doing this using PHP, however because YouTube restricts the maximum number of videos called, I have a hit a stumbling block. The maximum I can request is 50 whereas I have over 200 videos which I need to put in a list and I want to be able to do this dynamically.
I understand that I will have to loop the response, which is what I have done but is there a way it can be dynamically done?
If you could help me that would be great, my code is:
$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 />";
}
}
}
}
and so on...
If you could help me out, or at least point me in the right direction that would be g开发者_运维百科reat, thanks.
One way is to loop over requests, and then over each item in the request. Like this:
$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.)
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
精彩评论