How do I get a YouTube video thumbnail from the YouTube API?

后端 未结 30 2752
Happy的楠姐
Happy的楠姐 2020-11-21 07:06

If I have a YouTube video URL, is there any way to use PHP and cURL to get the associated thumbnail from the YouTube API?

30条回答
  •  暖寄归人
    2020-11-21 07:49

    You can use YouTube Data API to retrieve video thumbnails, caption, description, rating, statistics and more. API version 3 requires a key*. Obtain the key and create a videos: list request:

    https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID
    

    Example PHP Code

    $data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40");
    $json = json_decode($data);
    var_dump($json->items[0]->snippet->thumbnails);
    

    Output

    object(stdClass)#5 (5) {
      ["default"]=>
      object(stdClass)#6 (3) {
        ["url"]=>
        string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
        ["width"]=>
        int(120)
        ["height"]=>
        int(90)
      }
      ["medium"]=>
      object(stdClass)#7 (3) {
        ["url"]=>
        string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
        ["width"]=>
        int(320)
        ["height"]=>
        int(180)
      }
      ["high"]=>
      object(stdClass)#8 (3) {
        ["url"]=>
        string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
        ["width"]=>
        int(480)
        ["height"]=>
        int(360)
      }
      ["standard"]=>
      object(stdClass)#9 (3) {
        ["url"]=>
        string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
        ["width"]=>
        int(640)
        ["height"]=>
        int(480)
      }
      ["maxres"]=>
      object(stdClass)#10 (3) {
        ["url"]=>
        string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
        ["width"]=>
        int(1280)
        ["height"]=>
        int(720)
      }
    }
    

    * Not only that you need a key, you might be asked for billing information depending on the number of API requests you plan to make. However, few million requests per day are free.

    Source article.

提交回复
热议问题