W3docs

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

To get a thumbnail image for a YouTube video in PHP, you can use the file_get_contentsfunction to make a GET request to the videos.list method of the YouTube Data API.

To get a thumbnail image for a YouTube video in PHP, you can use the file_get_contents function to make a GET request to the videos.list method of the YouTube Data API.

Here's an example of how to do this:

How to get a thumbnail image for a YouTube video in PHP?

<?php

// Replace YOUR_API_KEY with your actual API key
$apiKey = 'YOUR_API_KEY';

// Replace VIDEO_ID with the ID of the video for which you want to get the thumbnail
$videoId = 'VIDEO_ID';

// Set the API endpoint for the videos.list method
$apiEndpoint = 'https://www.googleapis.com/youtube/v3/videos';

// Set the parameters for the API request
$params = [
    'id' => $videoId,
    'key' => $apiKey,
    'part' => 'snippet',
];

// Build the query string
$query = http_build_query($params);

// Make the GET request to the API endpoint
$response = file_get_contents($apiEndpoint . '?' . $query);

// Decode the JSON response
$responseData = json_decode($response, true);

// Validate response and extract thumbnail URL
if (isset($responseData['items'][0]['snippet']['thumbnails']['default']['url'])) {
    $thumbnailUrl = $responseData['items'][0]['snippet']['thumbnails']['default']['url'];
    echo '<img src="' . $thumbnailUrl . '" alt="Thumbnail">';
} else {
    echo 'Thumbnail not found or API error.';
}

?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This code makes a GET request to the videos.list method of the YouTube Data API, passing in the API key, the video ID, and the part parameter set to snippet. The API returns a JSON object containing data about the video, including the thumbnail image URL in the snippet.thumbnails.default.url field. The code then decodes the JSON response, validates that the items array exists, and extracts the thumbnail URL to display the image.

Note: allow_url_fopen must be enabled in your php.ini for file_get_contents to fetch remote URLs. For production applications, consider using cURL or a dedicated HTTP client for better error handling and performance.