Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed YouTube videos in PHP?

Can anyone give me an idea how can we show or embed a YouTube video if we just have the URL or the Embed code?

like image 549
Satish Ravipati Avatar asked Jan 05 '09 07:01

Satish Ravipati


People also ask

How do I embed a YouTube video dynamically?

YouTube provides video embedding feature to web page by using simple HTML iframe tag, which is very easy process for everyone. However embedding a YouTube video player while page loading slow down a web page's load performance especially if there are more than one videos embedded on the same page.

How do I embed a video in a URL?

You embed a video using a URL by copying the video's URL from your web browser's address bar while viewing the video and pasting URL on a line by itself in your post/page editor where you want the video to appear. For YouTube you use the video URL from “Share this video” under the Share option.

How do you embed a video in HTML?

To embed a video in an HTML page, use the <iframe> element. The source attribute included the video URL. For the dimensions of the video player, set the width and height of the video appropriately. The Video URL is the video embed link.


2 Answers

You have to ask users to store the 11 character code from the youtube video.

For e.g. http://www.youtube.com/watch?v=Ahg6qcgoay4

The eleven character code is : Ahg6qcgoay4

You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-

e.g. for Ahg6qcgoay4 it will be :

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object> 
like image 137
Alec Smart Avatar answered Sep 25 '22 13:09

Alec Smart


Do not store the embed code in your database -- YouTube may change the embed code and URL parameters from time to time. For example the <object> embed code has been retired in favor of <iframe> embed code. You should parse out the video id from the URL/embed code (using regular expressions, URL parsing functions or HTML parser) and store it. Then display it using whatever mechanism currently offered by YouTube API.

A naive PHP example for extracting the video id is as follows:

<?php     preg_match(         '/[\\?\\&]v=([^\\?\\&]+)/',         'http://www.youtube.com/watch?v=OzHvVoUGTOM&feature=channel',         $matches     );     // $matches[1] should contain the youtube id ?> 

I suggest that you look at these articles to figure out what to do with these ids:

  • Embed YouTube Videos, Playlists and More with IFrame Embeds

To create your own YouTube video player:

  • YouTube Embedded Player Parameters
  • YouTube JavaScript Player API Reference
like image 35
Salman A Avatar answered Sep 24 '22 13:09

Salman A