Search Videos by Keyword using PHP YouTube Data API

by Vincy. Last modified on July 8th, 2022.

If you want to list YouTube Videos on your web page, you need to access the Google API YouTube Data API library. In a previous tutorial, we have already seen how to use the YouTube Data API V3 library to get the Video title and description.

Using this API library, we can get other YouTube data resources like videos, playlists, channels and more. In this article, I have shown the code for getting a list of videos from YouTube by keywords.

In this example, I have created a filter with the search box. When the users enter and submit their keywords, I search YouTube via the YouTube Data API V3 library and get the list of videos. Then, I formed a video gallery with the resultant video list.

In PHP, I checked if the search keyword is not empty and proceeded with the library access to get the videos. I set the maximum number of results as a PHP constant and send this value to the API call.

Also, I have appended the search keyword and API key with the Google API URL. Then I fetch the remote content by using the PHP CURL script.

This screenshot shows the output with the video gallery by fetching YouTube videos by the searched keyword.

search-youtube-videos-by-keyword

HTML Filter to Submit Search Keywords

I have created a HTML filter to search for the YouTube videos by keyword. The user can submit the search keyword by using this filter. The posted keyword is validated on the server-side before processing it with the API call. After the form submission if no value is found in the search keyword input, then the validation error message will be updated in the browser.

Otherwise, the search keyword will be sent with the API call and the related videos are displayed in a gallery view. In the API call, the search keyword is sent by using the ‘q’ parameter.

<?php
    if (isset($_POST['submit']) )
     {
        $keyword = $_POST['keyword'];
               
        if (empty($keyword))
        {
            $response = array(
                  "type" => "error",
                  "message" => "Please enter the keyword."
                );
        } 
    }     
?>
<h2>Search Videos by keyword using YouTube Data API V3</h2>
<div class="search-form-container">
    <form id="keywordForm" method="post" action="">
        <div class="input-row">
            Search Keyword : <input class="input-field" type="search"
                id="keyword" name="keyword"
                placeholder="Enter Search Keyword">
        </div>

        <input class="btn-submit" type="submit" name="submit"
            value="Search">
    </form>
</div>

<?php 
if(!empty($response)) { 
?>
<div class="response <?php echo $response["type"]; ?>
    ">
    <?php echo $response["message"]; ?>
</div>
<?php 
}
?>

PHP CURL Request to Get YouTube Videos

In the following PHP CURL script, I have requested the YouTube Data API V3 access to get the videos by the search keyword. I am sending the search keyword with the API call to request a YouTube video list related to the keyword.

After fetching the remote data, the CURL response will return the video data. The CURL response will be parsed to get the video title and the description in the gallery. The video thumbnail is embedded using the iframe for each gallery tile.

<?php
if (isset($_POST['submit']) )
{
     
  if (!empty($keyword))
  {
    $apikey = 'YOUR API KEY'; 
    $googleApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' . $keyword . '&maxResults=' . MAX_RESULTS . '&key=' . $apikey;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $googleApiUrl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);

    curl_close($ch);
    $data = json_decode($response);
    $value = json_decode(json_encode($data), true);
?>

<div class="result-heading">About <?php echo MAX_RESULTS; ?> Results</div>
<div class="videos-data-container" id="SearchResultsDiv">

<?php
    for ($i = 0; $i < MAX_RESULTS; $i++) {
        $videoId = $value['items'][$i]['id']['videoId'];
        $title = $value['items'][$i]['snippet']['title'];
        $description = $value['items'][$i]['snippet']['description'];
        ?> 
    
<div class="video-tile">
<div  class="videoDiv">
    <iframe id="iframe" style="width:100%;height:100%" src="//www.youtube.com/embed/<?php echo $videoId; ?>" 
data-autoplay-src="//www.youtube.com/embed/<?php echo $videoId; ?>?autoplay=1"></iframe>         
</div>
<div class="videoInfo">
<div class="videoTitle"><b><?php echo $title; ?></b></div>
<div class="videoDesc"><?php echo $description; ?></div>
</div>
</div>
           <?php 
        }
    } 
           
}
?> 

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Search Videos by Keyword using PHP YouTube Data API”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page