Search Videos by Keyword using PHP YouTube Data API

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 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 keyword, 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 proceed 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, API key with the Google API URL. Then I fetch the remote content by using PHP CURL script.

HTML Filter to Submit Search Keyword

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 in the server-side before processing it with the API call. After form submit if no value 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 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 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.