YouTube Videos in PHP: Categories, Search and Suggestions

View: 397    Dowload: 0   Comment: 0   Post by: daii   Category: Php&mySql   Fields: none

File has been tested

In the first part, we introduced the YouTube API and built a small demo to list the most popular videos on YouTube. In this part, we will extend our application to have search functionality, and we’ll also list the available categories on YouTube to let the user narrow down their area of interest. Let’s get started.

Listing Categories

YouTube videos are grouped by categories. We can retrieve the list of categories for a certain country using their ISO code. The result can also be localized using an optional parameter like en_US, fr_FR, etc. You can read more in the documentation.

// app/Http/routes.php

Route::get('/categories', ['uses' => 'YouTubeAPIController@categories']);

// app/Http/Controllers/YouTubeAPIController.php

public function categories()
{
  $youtube = App::make('youtube');
  $categories = $youtube->videoCategories->listVideoCategories('snippet', ['regionCode' => 'MA']);

  dump($categories);
}
// app/Http/Controllers/YouTubeAPIController.php

public function categories()
{
  $youtube = App::make('youtube');
  $categories = $youtube->videoCategories->listVideoCategories('snippet', ['regionCode' => 'MA']);

  dump($categories);
}

As before, the first parameter is the part, and I used my country code as a filter. The result looks like the following.

Back to our demo, we need to use the list of categories and give the user the ability to filter the list of videos.

// app/Http/Controllers/YouTubeAPIController.php

public function videos()
{
  $options = ['chart' => 'mostPopular', 'maxResults' => 16];
  $regionCode = 'MA';
  $selectedCategory = 0;

  if (Input::has('page')) {
    $options['pageToken'] = Input::get('page');
  }

  if (Input::has('category')) {
    $selectedCategory = Input::get('category');
    $options['videoCategoryId'] = $selectedCategory;
  }

  $youtube = App::make('youtube');
  $categories = $youtube->videoCategories->listVideoCategories('snippet', ['regionCode' => $regionCode])->getItems();
  $videos = $youtube->videos->listVideos('id, snippet', $options);

  return view('videos', ['videos' => $videos, 'categories' => $categories, 'selectedCategory' => $selectedCategory]);
}

When the user selects a category, we pass the category ID as a parameter to the videos method. This should work fine with the pagination, so let’s see our view markup changes.

// resources/views/videos.blade.php

{!! Form::open(['route' => 'videos', 'name' => 'formCategory', 'class' => 'form-inline']) !!}
    Filter by category: 
    

{!! Form::close() !!}

When the user selects a category, we pass the category ID as a parameter to the videos method. This should work fine with the pagination, so let’s see our view markup changes.

// resources/views/videos.blade.php

{!! Form::open(['route' => 'videos', 'name' => 'formCategory', 'class' => 'form-inline']) !!}
    Filter by category: 
    
{!! Form::close() !!}


    getPrevPageToken() == null) class="disabled" @endif> Previous «
    getNextPageToken() == null) class="disabled" @endif> Next » 

The form is submitted on change event of the list of categories, and we make sure to pass the selected category along with the page token on the navigation. The zero category resets our filter.

Video Search

Searching is an important aspect of the YouTube platform, and we need to have this functionality in our demo. The user can search and paginate through the list of results.

// app/Http/routes.php

Route::any('/search', ['as' => 'search', 'uses' => 'YouTubeAPIController@search']);

// app/Http/Controllers/YouTubeAPIController.php

public function search()
{
  if (!Input::has('query')) {
    return view("search");
  }

  $options = ['maxResults' => 16, 'q' => Input::get("query")];
  if (Input::has('page')) {
    $options['pageToken'] = Input::get('page');
  }

  $youtube = App::make('youtube');
  $videos = $youtube->search->listSearch("snippet", $options);

  return view("search", ['videos' => $videos, 'query' => Input::get('query')]);
}

// app/Http/Controllers/YouTubeAPIController.php

public function search()
{
  if (!Input::has('query')) {
    return view("search");
  }

  $options = ['maxResults' => 16, 'q' => Input::get("query")];
  if (Input::has('page')) {
    $options['pageToken'] = Input::get('page');
  }

  $youtube = App::make('youtube');
  $videos = $youtube->search->listSearch("snippet", $options);

  return view("search", ['videos' => $videos, 'query' => Input::get('query')]);
}
// app/Http/Controllers/YouTubeAPIController.php

public function search()
{
  if (!Input::has('query')) {
    return view("search");
  }

  $options = ['maxResults' => 16, 'q' => Input::get("query")];
  if (Input::has('page')) {
    $options['pageToken'] = Input::get('page');
  }

  $youtube = App::make('youtube');
  $videos = $youtube->search->listSearch("snippet", $options);

  return view("search", ['videos' => $videos, 'query' => Input::get('query')]);
}

If the query parameter is not present, that means we need just to render an empty page with the search input, otherwise, we add the query parameter to the list of options and we see if we have a pagination parameter. The view is almost identical to the videos one.

// resources/views/search.blade.php

{!! Form::open(['route' => 'search', 'class' => 'form-inline']) !!}
    
    
{!! Form::close() !!}

@if(isset($videos))
    

    @foreach($videos as $video)
        {{ $video['snippet']['title'] }}
        {{ $video['snippet']['title'] }}
        @endforeach 
        getPrevPageToken() == null) class="disabled" @endif> Previous «
        getNextPageToken() == null) class="disabled" @endif> Next » 
    @else
    No result.
    @endif
  • @foreach($videos as $video)
    • {{ $video['snippet']['title'] }}

    • @endforeach
    • getPrevPageToken() == null) class="disabled" @endif> Previous «
    • getNextPageToken() == null) class="disabled" @endif> Next »
    @else

    No result.

    @endif

    You see that the videos result is identical to the video page, except that the $video->getId() method returns a resource, and you need to get the video ID using a chained call. YouTube API results have array access, so you can work with them as arrays instead of calling getter methods.
    The response also contains information about the video channel, creation date, quality, etc. You may use them to enrich your page.

    When you visit a single video page on YouTube, you see a list of suggestions based on your current video. The search endpoint offers this possibility through some options:

    // app/Http/Controllers/YouTubeAPIController.php
    
    public function video($id)
    {
      $options = ['maxResults' => 1, 'id' => $id];
    
      $youtube = App::make('youtube');
      $videos = $youtube->videos->listVideos('id, snippet, player, contentDetails, statistics, status', $options);
      $relatedVideos = $youtube->search->listSearch("snippet", ['maxResults' => 16, 'type' => 'video', 'relatedToVideoId' => $id]);
    
      if (count($videos->getItems()) == 0) {
        return redirect('404');
      }
    
      return view('video', ['video' => $videos[0], 'relatedVideos' => $relatedVideos]);
    }

    According to the documentation, you need to set the type parameter to video when you want to do a related video search. The search endpoint has a lot of options like restricting the search to a certain quality, a certain category or a certain channel, etc. Be sure to check the documentation for the list of available options.

    Extending the Demo

    Because we can’t cover everything in this tutorial, you can take the demo from here and start extending it with some new functionality. You can start by displaying video channel names and links under every video element, and when the user clicks on the link, redirect them to the /channel/channel_id route and only display the channel videos; you can group the video by playlists, etc.

    Quotas & Caching

    An important part of working with APIs are quotas. YouTube gives you 50,000,000 units/day, and as we said earlier, units are calculated per request and can be increased when you ask for more information. Some API calls cost more than others. For example, calls to the search endpoint cost 100 units. Apart from that, you are limited to 3000 requests/second/user.

    Etags Caching

    If you’ve noticed in the previous screenshots, we have an Etag attribute which stamps the current state of the entity result. This attribute can be sent inside the HTTP headers as described on the HTTP spec page and if the entity has changed you’ll get a refreshed version, otherwise you get a 304 (not modified) response. You can read more about optimization and performance in the documentation.

    Conclusion

    In this article, we introduced the YouTube API v3 and built a demo along the way. The API offers a lot of features, like working with user activities, playlists, channels, subscriptions, etc. Be sure to check the getting started guide to familiarize yourself with the limits and possibilities.

    You can check the final demo on Github, it includes an installation guide to get you started. If you have any comments or questions, don’t hesitate to post them below and I will do my best to answer them.

YouTube Videos in PHP: Categories, Search and Suggestions

In the first part, we introduced the YouTube API and built a small demo to list the most popular videos on YouTube. In this part, we will extend our application to have search functionality, and we’ll also list the available categories on YouTube to let the user narrow down their area of interest. Let’s get started.

Posted on 23-11-2015 

Comment:

To comment you must be logged in members.

Files with category

  • SimpleXML is a PHP extension that allows us to easily manipulate and get XML data

    SimpleXML is a PHP extension that allows us to easily manipulate and get XML data

    View: 234    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout. SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays...

  • How to use the PHP download file script? Class Download PHP

    How to use the PHP download file script? Class Download PHP

    View: 148    Download: 1   Comment: 0

    Category: Php&mySql     Fields: Other

    This is my favorite PHP download script. I’ve used a different more simple method until a client wanted to be able to allow their site visitors to download a large file from a password protected directory. The PHP script works on Apache web servers...

  • Installing OCI8 & PHP 7.2 on RHEL or CentOS 6

    Installing OCI8 & PHP 7.2 on RHEL or CentOS 6

    View: 290    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    You’ll need to stop Apache (web server) using the following command. In any Linux commands I show in this article, it presumes you aren’t logged in as the root user, so you will need to use sudo to issue privileged commands.

  • PHP source code: get content of google search

    PHP source code: get content of google search

    View: 241    Download: 2   Comment: 0

    Category: Php&mySql     Fields: Other

    How to get the results of google search and display on your website. This PHP code can do that. Refer to the following code.

  • PHP as a Scripting Language for C#

    PHP as a Scripting Language for C#

    View: 175    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    When creating .NET applications (including desktop and web applications), it may be useful to allow extending the application using some scripting language. The users of the application can write simple scripts to configure the application, modify...

  • How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    View: 4258    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    With the explosion of machine learning services in recent years, it has become easier than ever for developers to create “smart apps”. In this article, I’ll introduce you to Microsoft’s offering for providing machine-learning capabilities to apps.

  • How to MySqli Tutorial PHP MySqli Extension

    How to MySqli Tutorial PHP MySqli Extension

    View: 556    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    PHP provides three api to connect mysql Database.

  • Make Laravel Artisan Commands

    Make Laravel Artisan Commands

    View: 524    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow.

 
File suggestion for you
File top downloads
Codetitle.net - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.net Develope by Vinagon .Ltd