PHP – Using oEmbed API to Embed Videos

Posted in Web Development on 30 January 2012 0 comment

oEmbed is a format for allowing an embedded representation of a URL on third party sites. Which means, if we have a video page’s URL, we can easily get the video thumbnail photo, video title, HTML code to embed it in our website and more. But of course, the video site must have oEmbed support in order for us to do that. Check out for full documentation.

Let’s look at how YouTube oEmbed works

1. First, send a request to YouTube’s Oembed API page with a video URL (must be urlencoded) as parameter and we also specified that we want it to be returned in json format.

2. You will then see a long json-encoded string which contains all information about the video.

3. Next thing you need to do is just simply json-decode the string using your programming language, then you are free to use the information. We will see how to do that in PHP.

Using Oembed to Embed Youtube Videos in PHP

$videourl = '';
$json = @file_get_contents(''.urlencode($videourl).'&format=json');
$decode = json_decode($json, true);
if ($decode == null || !$decode) {
	$error = true;
	//error control here
} else {
	$thumb = $decode['thumbnail_url'];
	$html = $decode['html'];

It’s pretty straightforward and self-explanatory:

  • First, we send a url request to YouTube’s obembed API page using file_get_contents() function.
  • Second, we decode the response using json_decode() function which convert json format to array.
  • Third, if there is no error in decoding, we then assign $thumb and $html and use it in our website or program.

Extra: If you want to limit the embedded video’s width or height

You can specify the max height or max width by appending the maxwidth or maxheight parameters to the oembed URL. (Please note that this cannot resize a smaller video to bigger size)

For example, from our example above, to specify max width of 300 pixels:

You should notice the video embedding code (iframe) is now limited to width of 300 pixels.

How do I embed videos from other video sites like Vimeo?

Most of the popular video sites has oEmbed support just like YouTube. For example, by googling “vimeo oembed” we found vimeo oembed documentation.

In vimeo, this is the URL we should send our request to:

More details about oEmbed API page for other video sites will be covered in our next blog post (coming soon).


Posted by Zen on 30 January 2012 • 31,748 visits 0 comment
Tags :

or Subscribe to specific category only :


No comment yet. Be the first to leave a comment!

Leave a Reply

You must be logged in to post a comment.

Previous Post
Next Post