Posted By

frankyfish on 03/17/10


Tagged

php object video embed flickr photo vimeo YouTube oembed


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

nfreear


oembed


 / Published in: PHP
 

Function to use the oembed services in php

  1. // Curl helper function
  2. function curl_get($url) {
  3. $curl = curl_init($url);
  4. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  5. curl_setopt($curl, CURLOPT_TIMEOUT, 30);
  6. $return = curl_exec($curl);
  7. curl_close($curl);
  8. return $return;
  9. }
  10.  
  11. // Usage
  12. // todo better handling and detection of the service and adding some more...
  13. // getOEmbed("any service url"); -> This return an information array of the media
  14. // getOEmbed("any service url", true); -> This return the html for the media
  15. // getOEmbed("any service url", array("maxwidth"=>300)); -> This return an information array of the media with the parameter
  16. // getOEmbed("any service url", array("maxwidth"=>300), true); -> This return the html for the media with the parameter
  17. function getOEmbed($url=null, $params=null, $returnHtml=null) {
  18. if($url == null) return;
  19. if($params == null) $params = array();
  20. if(is_bool($params) && $returnHtml==null) {$returnHtml = $params;$params = array();}
  21.  
  22. $oEmbedUrl = null;
  23. $services = array(
  24. "vimeo.com" => "http://www.vimeo.com/api/oembed.json?url=",
  25. "youtube.com" => "http://www.youtube.com/oembed?url=",
  26. "flickr.com/photos" => "http://www.flickr.com/services/oembed/?url="
  27. );
  28.  
  29. // Try to find the services based on the domain name with the one in the services array
  30. foreach($services as $servicesName => $servicesUrl) {
  31. if(strpos($url, $servicesName) !== false) {
  32. $oEmbedUrl = $servicesUrl.$url;
  33. }
  34. }
  35.  
  36. // Check for the oembed link embeded exists in the page
  37. if($oEmbedUrl == null) {
  38. $data = curl_get($url);
  39. $pattern = "/type=\"application\/json\+oembed\" href=[\\\"']?(.[^\\\"']*)[\\\"']?/i";
  40. preg_match_all($pattern, $data, $oembedLinks);
  41. if(isset($oembedLinks[1][0])) $oEmbedUrl = $oembedLinks[1][0];
  42. }
  43.  
  44. // If found nothing at that point, use the oohembed.com service.
  45. if($oEmbedUrl == null) {
  46. $oEmbedUrl = "http://oohembed.com/oohembed/?url=".$url;
  47. }
  48. $param = "";
  49. foreach($params as $key => $value) $param .= "&".$key."=".$value;
  50. $ret = json_decode(curl_get($oEmbedUrl.$param."&format=json"));
  51. if($returnHtml) {
  52. if($ret->type == "video") {
  53. return $ret->html;
  54. } else {
  55. return "<img src=\"".$ret->url."\" width=\"".$ret->width."\" height=\"".$ret->height."\" />";
  56. }
  57. } else {
  58. return $ret;
  59. }
  60.  
  61. }

Report this snippet  

You need to login to post a comment.