YouTube API-使用PHP和xml用户提要检索最后上传的视频


YouTube API - using PHP and xml user feed to retrieve last video uploads

所以我试图通过提要获得最后5个YouTube用户上传,最后我在网上找到了以下代码:

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++;
}
}

问题是它显示了最后上传的视频5次,实际上我希望它检索最后5个视频,而不是重复一个。

最后一句话:非常感谢!

您有两个彼此内部的循环。

一个从0到5计数:

for($i = 0; $i < 5; )
// some code
$i++; // this could just be in the for(), by the way

在里面,你有一些代码,每次都做同样的事情,忽略计数器。它包含一个循环,依次查看每个视频:

foreach ($sxml->entry as $entry) {

但在它有机会查看第一个条目以外的任何内容之前,你就突破了内部循环:

break;

你只需要一个或另一个循环。

使用计数器方法,可以使用$i引用XML:中的特定条目

$sxml = simplexml_load_file($feedURL);
for($i = 0; $i < 5; $i++) {
    $entry = $sxml->entry[$i];
    // display a video
}

注意,如果条目少于5个,则此操作将失败;你可以通过测试isset($sxml->entry[$i])来解决这个问题。

使用foreach循环,当你到达第五个:时,你可以计算出你有多少视频得到了回应和break

$sxml = simplexml_load_file($feedURL);
$i = 0;
foreach ($sxml->entry as $entry) {
    $i++;
    // display a video
    if ( $i == 5 ) {
        break;
    }
}