2011-09-29 32 views
2

我相信這可能是一個簡單的解決方案,但我看不到我的錯誤。我正在向YouTube進行API調用,以使用視頻ID獲取有關YouTube視頻的一些基本信息;特別是我想要的是(1)標題,(2)描述,(3)標籤和(4)縮略圖。Youtube API:通過PHP中的curl丟失數據?

當我通過Web瀏覽器加載API url時,我看到所有的數據。我不想在此問題中粘貼整個回覆,但將以下網址粘貼到瀏覽器中,您將看到我看到的內容:http://gdata.youtube.com/feeds/api/videos/_83A00a5mG4

如果仔細觀察,您會看到媒體:縮略圖,媒體:關鍵字,內容等。我想要的一切都在那裏。現在的麻煩...

當我通過下面的函數(我從Vimeo API複製...)加載相同的網址,縮略圖和關鍵字根本就不存在。

function curl_get($url) { 
    $curl = curl_init($url); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); 
    $return = curl_exec($curl); 
    curl_close($curl); 
    return $return; 
} 

// youtube_get_ID is defined elsewhere... 

$request_url = "http://gdata.youtube.com/feeds/api/videos/" . youtube_get_ID($url); 
$video_data = simplexml_load_string(curl_get($request_url)); 

這些功能做給我一些數據的響應,但關鍵字和縮略圖失蹤。任何人都可以告訴我爲什麼我的縮略圖和關鍵字缺失?感謝您的任何幫助!

回答

0

這是link for documentation就可以了。

下面是我寫了一個函數:

function get_youtube_videos($max_number, $user_name) { 
    $xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/' . $user_name . '/uploads?max-results=' . $max_number); 

    $server_time = $xml->updated; 

    $return = array(); 

    foreach ($xml->entry as $video) { 
     $vid = array(); 

     $vid['id'] = substr($video->id,42); 
     $vid['title'] = $video->title; 
     $vid['date'] = $video->published; 
     //$vid['desc'] = $video->content; 

     // get nodes in media: namespace for media information 
     $media = $video->children('http://search.yahoo.com/mrss/'); 

     // get the video length 
     $yt = $media->children('http://gdata.youtube.com/schemas/2007'); 
     $attrs = $yt->duration->attributes(); 
     $vid['length'] = $attrs['seconds']; 

     // get video thumbnail 
     $attrs = $media->group->thumbnail[0]->attributes(); 
     $vid['thumb'] = $attrs['url']; 

     // get <yt:stats> node for viewer statistics 
     $yt = $video->children('http://gdata.youtube.com/schemas/2007'); 
     $attrs = $yt->statistics->attributes(); 
     $vid['views'] = $attrs['viewCount']; 

     array_push($return, $vid); 
    } 

    return $return; 
} 

而這裏的實現:

$max_videos = 9; 
$videos = get_youtube_videos($max_videos, 'thelonelyisland'); 

foreach($videos as $video) { 
    echo $video['title'] . '<br/>'; 
    echo $video['id'] . '<br/>'; 
    echo $video['date'] . '<br/>'; 
    echo $video['views'] . '<br/>'; 
    echo $video['thumb'] . '<br/>'; 
    echo $video['length'] . '<br/>'; 
    echo '<hr/>'; 
} 
+0

如果YouTube的下跌,或不及時迴應,會發生什麼。這失敗了。 curl會是一個更好的選項,可以通過超時設置來檢索信息。 – deweydb