Skip to content

Instantly share code, notes, and snippets.

@jelmervdl
Created February 7, 2011 18:01
Show Gist options
  • Save jelmervdl/814839 to your computer and use it in GitHub Desktop.
Save jelmervdl/814839 to your computer and use it in GitHub Desktop.
Simple interface for getting oembed data from supported (and unsupported) sites.
<?php
function oembed_get_data($video_url, array $params = array(), &$error = null)
{
$html = @file_get_contents($video_url);
if (!$html)
{
$error = 'Could not download video page';
return false;
}
$links = oebmed_parse_links($html);
foreach ($links as $link)
{
if (!isset($link['type']) || empty($link['href']))
continue;
$oembed_url = $link['href'];
if (!empty($params))
$oembed_url .= (strpos($oembed_url, '?') === false ? '?' : '&')
. http_build_query($params);
if ($link['type'] == 'application/xml+oembed' || $link['type'] == 'text/xml+oembed')
return oembed_get_xml_data($link['href'], $error);
if ($link['type'] == 'application/json+oembed')
return oembed_get_json_data($link['href'], $error);
}
// fallback using embed.ly
$params = array_merge($params, array('url' => $video_url, 'format' => 'json'));
$embedly_uri = 'http://api.embed.ly/1/oembed?' . http_build_query($params);
return oembed_get_json_data($embedly_uri, $error);
}
function oebmed_parse_links($html)
{
$links = array();
if (preg_match_all('{<link ([^<>]+)/?>}i', $html, $matches))
foreach ($matches[1] as $attributes_str)
{
preg_match_all('{([a-z]+)=(["\'])(.+?)\2}i', $attributes_str, $amatches, PREG_SET_ORDER);
$attributes = array();
foreach ($amatches as $amatch)
$attributes[$amatch[1]] = html_entity_decode($amatch[3]);
$links[] = $attributes;
}
return $links;
}
function oembed_get_xml_data($oembed_url, &$error = null)
{
$xml = @simplexml_load_file($oembed_url);
if (!$xml)
{
$error = 'Could not parse or load oembed xml data';
return false;
}
$data = new stdClass;
foreach ($xml as $property => $value)
$data->$property = (string) $value;
return $data;
}
function oembed_get_json_data($oembed_url, &$error = null)
{
$json = @file_get_contents($oembed_url);
if (!$json)
{
$error = 'Could not download oembed json data';
return false;
}
$data = @json_decode($json);
if (!$data)
{
$error = 'Could not parse oembed json data';
return false;
}
return (object) $data;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment