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

后端 未结 30 2684
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:44

    If you want the biggest image from YouTube for a specific video ID, then the URL should be something like this:

    http://i3.ytimg.com/vi/SomeVideoIDHere/0.jpg
    

    Using the API, you can pick up default thumbnail image. Simple code should be something like this:

    //Grab the default thumbnail image
    $attrs = $media->group->thumbnail[1]->attributes();
    $thumbnail = $attrs['url'];
    $thumbnail = substr($thumbnail, 0, -5);
    $thumb1 = $thumbnail."default.jpg";
    
    // Grab the third thumbnail image
    $thumb2 = $thumbnail."2.jpg";
    
    // Grab the fourth thumbnail image.
    $thumb3 = $thumbnail."3.jpg";
    
    // Using simple cURL to save it your server.
    // You can extend the cURL below if you want it as fancy, just like
    // the rest of the folks here.
    
    $ch = curl_init ("$thumb1");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    
    // Using fwrite to save the above
    $fp = fopen("SomeLocationInReferenceToYourScript/AnyNameYouWant.jpg", 'w');
    
    // Write the file
    fwrite($fp, $rawdata);
    
    // And then close it.
    fclose($fp);
    

提交回复
热议问题