[PHP & JavaScript] How To Parse Youtube URL to Get Video ID, Thumbnail Image, or Embed Code
Hello, sometime we need to parse Youtube URL to get video ID, thumbnail image, or embed code automatically with PHP. To do so, I have created a function parse_youtube_url();
With this function we can:
- Get video ID
- Get Embed code
- Get Thumbnail or HQ Thumbnail URL
Check this out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/* * parse_youtube_url() PHP function * Author: takien * URL: http://takien.com * * @param string $url URL to be parsed, eg: * http://youtu.be/zc0s358b3Ys, * http://www.youtube.com/embed/zc0s358b3Ys * http://www.youtube.com/watch?v=zc0s358b3Ys * @param string $return what to return * - embed, return embed code * - thumb, return URL to thumbnail image * - hqthumb, return URL to high quality thumbnail image. * @param string $width width of embeded video, default 560 * @param string $height height of embeded video, default 349 * @param string $rel whether embeded video to show related video after play or not. */ function parse_youtube_url($url,$return='embed',$width='',$height='',$rel=0){ $urls = parse_url($url); //url is http://youtu.be/xxxx if($urls['host'] == 'youtu.be'){ $id = ltrim($urls['path'],'/'); } //url is http://www.youtube.com/embed/xxxx else if(strpos($urls['path'],'embed') == 1){ $id = end(explode('/',$urls['path'])); } //url is xxxx only else if(strpos($url,'/')===false){ $id = $url; } //http://www.youtube.com/watch?feature=player_embedded&v=m-t4pcO99gI //url is http://www.youtube.com/watch?v=xxxx else{ parse_str($urls['query']); $id = $v; if(!empty($feature)){ $id = end(explode('v=',$urls['query'])); } } //return embed iframe if($return == 'embed'){ return '</pre> <iframe src="http://www.youtube.com/embed/'.$id.'?rel='.$rel.'" frameborder="0" width="'.($width?$width:560).'" height="'.($height?$height:349).'"></iframe> <pre>'; } //return normal thumb else if($return == 'thumb'){ return 'http://i1.ytimg.com/vi/'.$id.'/default.jpg'; } //return hqthumb else if($return == 'hqthumb'){ return 'http://i1.ytimg.com/vi/'.$id.'/hqdefault.jpg'; } // else return id else{ return $id; } } |
/*
* parse_youtube_url() PHP function
* Author: takien
* URL: http://takien.com
*
* @param string $url URL to be parsed, eg:
* http://youtu.be/zc0s358b3Ys,
* http://www.youtube.com/embed/zc0s358b3Ys
* http://www.youtube.com/watch?v=zc0s358b3Ys
* @param string $return what to return
* - embed, return embed code
* - thumb, return URL to thumbnail image
* - hqthumb, return URL to high quality thumbnail image.
* @param string $width width of embeded video, default 560
* @param string $height height of embeded video, default 349
* @param string $rel whether embeded video to show related video after play or not.
*/
function parse_youtube_url($url,$return='embed',$width='',$height='',$rel=0){
$urls = parse_url($url);
//url is http://youtu.be/xxxx
if($urls['host'] == 'youtu.be'){
$id = ltrim($urls['path'],'/');
}
//url is http://www.youtube.com/embed/xxxx
else if(strpos($urls['path'],'embed') == 1){
$id = end(explode('/',$urls['path']));
}
//url is xxxx only
else if(strpos($url,'/')===false){
$id = $url;
}
//http://www.youtube.com/watch?feature=player_embedded&v=m-t4pcO99gI
//url is http://www.youtube.com/watch?v=xxxx
else{
parse_str($urls['query']);
$id = $v;
if(!empty($feature)){
$id = end(explode('v=',$urls['query']));
}
}
//return embed iframe
if($return == 'embed'){
return '</pre>
<iframe src="http://www.youtube.com/embed/'.$id.'?rel='.$rel.'" frameborder="0" width="'.($width?$width:560).'" height="'.($height?$height:349).'"></iframe>
<pre>';
}
//return normal thumb
else if($return == 'thumb'){
return 'http://i1.ytimg.com/vi/'.$id.'/default.jpg';
}
//return hqthumb
else if($return == 'hqthumb'){
return 'http://i1.ytimg.com/vi/'.$id.'/hqdefault.jpg';
}
// else return id
else{
return $id;
}
}
1 2 3 4 |
<?php echo parse_youtube_url('http://youtu.be/zc0s358b3Ys','hqthumb'); //return http://i1.ytimg.com/vi/zc0s358b3Ys/hqdefault.jpg echo parse_youtube_url('http://www.youtube.com/watch?v=zc0s358b3Ys','embed'); //return embed code (iframe) ?> |
<?php
echo parse_youtube_url('http://youtu.be/zc0s358b3Ys','hqthumb'); //return http://i1.ytimg.com/vi/zc0s358b3Ys/hqdefault.jpg
echo parse_youtube_url('http://www.youtube.com/watch?v=zc0s358b3Ys','embed'); //return embed code (iframe)
?>
Note:
Please report if there any error in the code you copied from here, because it might has changed by WordPress during saved/published.
Thank you.
Update: June 16, 2012
Youtube Parser Class
Helo all, I have created the new version of Youtube parser, now use class. This version allow you to parse or extract Youtube ID, Thumbnails and Embed Code from a page or long content (not only single link)
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?php /* * YoutubeParser() PHP class * @author: takien * @version: 1.0 * @date: June 16, 2012 * URL: http://takien.com/864/php-how-to-parse-youtube-url-to-get-video-id-thumbnail-image-or-embed-code.php * * @param string $source content source to be parsed, eg: a string or page contains youtube links or videos. * @param boolean $unique whether the return should be unique (duplicate result will be removed) * @param boolean $suggested whether show suggested video after finished playing * @param boolean $https whether use https or http, default false ( http ) * @param string $width width of embeded video, default 420 * @param string $height height of embeded video, default 315 * @param boolean $privacy whether to use 'privacy enhanced mode or not', * if true then the returned Youtube domain would be youtube-nocookie.com */ class YoutubeParser{ var $source = ''; var $unique = false; var $suggested = false; var $https = false; var $privacy = false; var $width = 420; var $height = 315; function __construct(){ } function set($key,$val){ return $this->$key = $val; } function getall(){ $return = Array(); $domain = 'http'.($this->https?'s':'').'://www.youtube'.($this->privacy?'-nocookie':'').'.com'; $size = 'width="'.$this->width.'" height="'.$this->height.'"'; preg_match_all('/(youtu.be\/|\/watch\?v=|\/embed\/)([a-z0-9\-_]+)/i',$this->source,$matches); if(isset($matches[2])){ if($this->unique){ $matches[2] = array_values(array_unique($matches[2])); } foreach($matches[2] as $key=>$id) { $return[$key]['id'] = $id; $return[$key]['embed'] = '<iframe '.$size.' src="'.$domain.'/embed/'.$id.($this->suggested?'':'?rel=0').'" frameborder="0" allowfullscreen></iframe>'; $return[$key]['embedold'] = '<object '.$size.'> <param name="movie" value="'.$domain.'/v/'.$id.'?version=3'.($this->suggested?'':'&rel=0').'"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="'.$domain.'/v/'.$id.'?version=3'.($this->suggested?'':'&rel=0').'" type="application/x-shockwave-flash" '.$size.' allowscriptaccess="always" allowfullscreen="true"></embed> </object>'; $return[$key]['thumb'] = 'http://i4.ytimg.com/vi/'.$id.'/default.jpg'; $return[$key]['hqthumb'] = 'http://i4.ytimg.com/vi/'.$id.'/hqdefault.jpg'; } } return $return; } } |
<?php
/*
* YoutubeParser() PHP class
* @author: takien
* @version: 1.0
* @date: June 16, 2012
* URL: http://takien.com/864/php-how-to-parse-youtube-url-to-get-video-id-thumbnail-image-or-embed-code.php
*
* @param string $source content source to be parsed, eg: a string or page contains youtube links or videos.
* @param boolean $unique whether the return should be unique (duplicate result will be removed)
* @param boolean $suggested whether show suggested video after finished playing
* @param boolean $https whether use https or http, default false ( http )
* @param string $width width of embeded video, default 420
* @param string $height height of embeded video, default 315
* @param boolean $privacy whether to use 'privacy enhanced mode or not',
* if true then the returned Youtube domain would be youtube-nocookie.com
*/
class YoutubeParser{
var $source = '';
var $unique = false;
var $suggested = false;
var $https = false;
var $privacy = false;
var $width = 420;
var $height = 315;
function __construct(){
}
function set($key,$val){
return $this->$key = $val;
}
function getall(){
$return = Array();
$domain = 'http'.($this->https?'s':'').'://www.youtube'.($this->privacy?'-nocookie':'').'.com';
$size = 'width="'.$this->width.'" height="'.$this->height.'"';
preg_match_all('/(youtu.be\/|\/watch\?v=|\/embed\/)([a-z0-9\-_]+)/i',$this->source,$matches);
if(isset($matches[2])){
if($this->unique){
$matches[2] = array_values(array_unique($matches[2]));
}
foreach($matches[2] as $key=>$id) {
$return[$key]['id'] = $id;
$return[$key]['embed'] = '<iframe '.$size.' src="'.$domain.'/embed/'.$id.($this->suggested?'':'?rel=0').'" frameborder="0" allowfullscreen></iframe>';
$return[$key]['embedold'] = '<object '.$size.'>
<param name="movie" value="'.$domain.'/v/'.$id.'?version=3'.($this->suggested?'':'&rel=0').'"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="'.$domain.'/v/'.$id.'?version=3'.($this->suggested?'':'&rel=0').'" type="application/x-shockwave-flash" '.$size.' allowscriptaccess="always" allowfullscreen="true"></embed>
</object>';
$return[$key]['thumb'] = 'http://i4.ytimg.com/vi/'.$id.'/default.jpg';
$return[$key]['hqthumb'] = 'http://i4.ytimg.com/vi/'.$id.'/hqdefault.jpg';
}
}
return $return;
}
}
Example usage:
Parse long content:
1 2 3 4 5 6 7 8 9 10 |
$content = 'This is the example content contains various Youtube URLS http://www.youtube.com/watch?v=R55e-uHQna0&feature=topvideos http://www.youtube.com/watch?v=iP526fG_M0Y <p><iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/26YwnQijaOg" frameborder="0" allowfullscreen></iframe></p> <p>Lorem ipsum dolor sit amet</p> http://www.youtube.com/embed/26YwnQijaOg Lorem ipsum dolor sit amet http://youtu.be/1u7a5otGnFc Lorem ipsum dolor sit amet http://www.youtube.com/watch?v=CYxw78Fhaug&feature=g-logo'; $youtube = new YoutubeParser; $youtube->set('source',$content); $youtube->set('unique',true); echo'<pre>'; print_r($youtube->getall()); echo'</pre>'; |
$content = 'This is the example content contains various Youtube URLS http://www.youtube.com/watch?v=R55e-uHQna0&feature=topvideos http://www.youtube.com/watch?v=iP526fG_M0Y <p><iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/26YwnQijaOg" frameborder="0" allowfullscreen></iframe></p> <p>Lorem ipsum dolor sit amet</p>
http://www.youtube.com/embed/26YwnQijaOg Lorem ipsum dolor sit amet http://youtu.be/1u7a5otGnFc Lorem ipsum dolor sit amet http://www.youtube.com/watch?v=CYxw78Fhaug&feature=g-logo';
$youtube = new YoutubeParser;
$youtube->set('source',$content);
$youtube->set('unique',true);
echo'<pre>';
print_r($youtube->getall());
echo'</pre>';
Parse single link:
1 2 3 4 5 6 |
$youtube = new YoutubeParser; $youtube->set('source','http://www.youtube.com/watch?v=R55e-uHQna0&feature=topvideos'); echo'<pre>'; print_r($youtube->getall()); echo'</pre>'; |
$youtube = new YoutubeParser;
$youtube->set('source','http://www.youtube.com/watch?v=R55e-uHQna0&feature=topvideos');
echo'<pre>';
print_r($youtube->getall());
echo'</pre>';
Update Nov 17, 2012: Get YouTube ID using JavaScript:
Hello, I write another snippet, Get YouTube ID from various YouTube URL using JavaScript
Or check out the gist here: https://gist.github.com/4077195


