Saturday, January 17, 2009

Php - Embed Youtube , Metacafe Videos in your website using Php

To embed a YouTube or MetaCafe video in your webpage by providing the url of the video page. It uses regular expression to get the id of the youtube video and id and name of the Metacafe video, which is used to generate the code for embedding the video. The generated code is compatible with the code provided by Youtube and metacafe.

To embed a video, pass the url of video page to the function embedVideo.


<?php
function embedVideo($url){
    if(
preg_match("#http://(.*)\.youtube\.com/watch\?v=(.*)(&(.*))?#", $url, $matches)){
       
?>
        <object width="425" height="344">
        <param name="movie" value="http://www.youtube.com/v/<?php echo $matches[2];?>&hl=en&fs=1"></param>
        <param name="allowFullScreen" value="true"></param>
        <param name="allowscriptaccess" value="always"></param>
        <embed src="http://www.youtube.com/v/<?php echo $matches[2];?>&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>
           </object>
       <?php
   
}elseif(preg_match("#http://www\.metacafe\.com/watch/(([^/].*)/([^/].*))/?#", $url, $matches)){
       
?>
        <embed flashVars="playerVars=showStats=no|autoPlay=no|videoTitle="  src="http://www.metacafe.com/fplayer/<?php echo $matches[1];?>.swf" width="400" height="348" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed>
       <?php
   
}
}
$youtubeVideo1 = 'http://in.youtube.com/watch?v=Km7PcdMzaN4';
$youtubeVideo2 = 'http://in.youtube.com/watch?v=xNi7QwAL3XY&feature=dir';
$metacafeVideo1 = 'http://www.metacafe.com/watch/2215104/amazing_video/';
$metacafeVideo2 = 'http://www.metacafe.com/watch/2204556/sensational_cars_of_the_future/';

embedVideo($youtubeVideo1);
embedVideo($youtubeVideo2);
embedVideo($metacafeVideo1);
embedVideo($metacafeVideo2);
?>

No comments: