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?

12/13/2014 5:04:38 PM

Accepted Answer

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

For e.g.

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="" type="application/x-shockwave-flash"><param name="src" value="" /></object>
1/5/2009 7:30:25 AM

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:

    // $matches[1] should contain the youtube id

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

To create your own YouTube video player:

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow