Getting title and description of embedded YouTube video

后端 未结 7 1760
抹茶落季
抹茶落季 2021-02-05 12:36

On a site I\'m developing I embed videos from YouTube and want to get the video title and its description.

How do I get that information?

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 13:12

    Youtube API V2.0 has been deprecated. It shows some wrong value for title "youtube.com/devicesupport" . pLease switch on to API V3.0

    YOu can refer the following PHP code and modify yours in js or jquery as per your needs..

    function youtube_title($id) {
     $id = 'YOUTUBE_ID';
    // returns a single line of JSON that contains the video title. Not a giant request.
    $videoTitle = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$id."&key=YOUR_API_KEY&fields=items(id,snippet(title),statistics)&part=snippet,statistics");
    // despite @ suppress, it will be false if it fails
    if ($videoTitle) {
    $json = json_decode($videoTitle, true);
    
    return $json['items'][0]['snippet']['title'];
    } else {
    return false;
    }
    }
    

    update:

    Jquery code to get the title-

     $.getJSON('https://www.googleapis.com/youtube/v3/videos?id={VIDEOID}&key={YOUR API KEY}&part=snippet&callback=?',function(data){
        if (typeof(data.items[0]) != "undefined") {
            console.log('video exists ' + data.items[0].snippet.title);
           } else {
            console.log('video not exists');
         }   
        });
    

提交回复
热议问题