Advertisement
Muskie

YouTube Search Function

Feb 17th, 2013
492
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.83 KB | None | 0 0
  1. /**
  2.  * This method searches YouTube and potentially eventually other video services for a video
  3.  * clip featuring the passed in subject.  Then it returns the HTML for an embeddable player
  4.  * to play that video.
  5.  *
  6.  * @param string
  7.  *
  8.  * @return string
  9.  */
  10. public function embeddableVideoClipFor($searchString)
  11. {
  12.     // Previous experience revealed that video search is not perfect, in that for given
  13.         // keywords the top result isn't always accurate.
  14.     $embeddableVideoClipHTML = NULL;
  15.            
  16.     // Further details on searching YouTube http://www.ibm.com/developerworks/xml/library/x-youtubeapi/
  17.     // This was working well for over two years but had to be revised to use version 2 of API
  18.     // May switch to Zend or version 3.0 of Google/YouTube API...
  19.            
  20.     $vq = $searchString;
  21.     $vq = preg_replace('/[[:space:]]+/', ' ', trim($vq));
  22.         $vq = urlencode($vq);
  23.         $feedURL = 'http://gdata.youtube.com/feeds/api/videos?q=' . $vq . '&safeSearch=none&orderby=relevance&v=2';
  24.          
  25.     // read feed into SimpleXML object
  26.     try
  27.     {
  28.         $youTubeXML = simplexml_load_file($feedURL);
  29.     }
  30.     catch(Exception $e)
  31.     {  
  32.         // This rarely throws an error, but when it does, I just pretend I can't find a video clip
  33.         $youTubeXML = NULL;
  34.     }  
  35.            
  36.     if(($youTubeXML != NULL) && ( ! empty($youTubeXML->entry->link[0]['href'])))
  37.     {
  38.         $videoLink = $youTubeXML->entry->link[0]['href'];  
  39.         // This is not enough, I need to trim the beginning and end off this to just get the video code
  40.         $trimedURL = str_replace('http://www.youtube.com/watch?v=', '' , $videoLink);
  41.         $videoCode = str_replace('&feature=youtube_gdata', '', $trimedURL);
  42.         $embeddableVideoClipHTML = '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/' . $videoCode . '"frameborder="0" allowfullscreen>';
  43.     }
  44.            
  45.     return $embeddableVideoClipHTML;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement