so I was trying to get last 5 YouTube user uploads through feed, and I ended with this code found online:
function yt_last_5() {
for($i = 0; $i < 5; ){
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/users/' . yt_user_id(). '/uploads?max-results=5';
$sxml = simplexml_load_file($feedURL);
foreach ($sxml->entry as $entry) {
$media = $entry->children('media', true);
$url = (string)$media->group->player->attributes()->url;
$index = strrpos($url, "&");
$url = substr($url, 0, $index);
$index = strrpos($url, "watch");
$url = substr($url, 0, $index) . "v/" . substr($url, $index + 8, strlen($url) - ($index + 8));
echo '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="250" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="' . $url . '" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="400" height="250" src="' . $url . '" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />';
break;
}
$i++;
}
}
The problem is that it shows the last uploaded video 5 times, actually I want it to retrieve the last 5 videos instead of repeating a single one.
last word: Thanks a lot!
You have two loops inside each other.
One counts from 0 to 5:
for($i = 0; $i < 5; )
// some code
$i++; // this could just be in the for(), by the way
Inside that, you have some code which does the same thing every time, ignoring the counter. That contains a loop which looks at each video in turn:
foreach ($sxml->entry as $entry) {
But before it has a chance to look at anything other than the first entry, you break out of the inner loop:
break;
You only need one loop or the other.
Using the counter approach, you could use $i
to reference a particular entry in the XML:
$sxml = simplexml_load_file($feedURL);
for($i = 0; $i < 5; $i++) {
$entry = $sxml->entry[$i];
// display a video
}
Beware that this will fail if there are ever less than 5 entries; you could fix that by testing isset($sxml->entry[$i])
.
Using the foreach
loop, you could count how many videos you've echoed and break
when you get to the 5th:
$sxml = simplexml_load_file($feedURL);
$i = 0;
foreach ($sxml->entry as $entry) {
$i++;
// display a video
if ( $i == 5 ) {
break;
}
}