PHP 透过oEmbed

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 透过oEmbed相关的知识,希望对你有一定的参考价值。

// Curl helper function
function curl_get($url) {
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_TIMEOUT, 30);
	$return = curl_exec($curl);
	curl_close($curl);
	return $return;
}

// Usage
// todo better handling and detection of the service and adding some more...
// getOEmbed("any service url"); -> This return an information array of the media
// getOEmbed("any service url", true); -> This return the html for the media
// getOEmbed("any service url", array("maxwidth"=>300)); -> This return an information array of the media with the parameter
// getOEmbed("any service url", array("maxwidth"=>300), true); -> This return the html for the media with the parameter
function getOEmbed($url=null, $params=null, $returnHtml=null) {
	if($url == null) return;
	if($params == null) $params = array();
	if(is_bool($params) && $returnHtml==null) {$returnHtml = $params;$params = array();}

	$oEmbedUrl = null;
	$services = array(
		"vimeo.com" => "http://www.vimeo.com/api/oembed.json?url=",
		"youtube.com" => "http://www.youtube.com/oembed?url=",
		"flickr.com/photos" => "http://www.flickr.com/services/oembed/?url="
	);
	
	// Try to find the services based on the domain name with the one in the services array
	foreach($services as $servicesName => $servicesUrl) {
		if(strpos($url, $servicesName) !== false) {
			$oEmbedUrl = $servicesUrl.$url;
		}
	}
	
	// Check for the oembed link embeded exists in the page
	if($oEmbedUrl == null) {
		$data = curl_get($url);
		$pattern = "/type=\"application\/json\+oembed\" href=[\\\"']?(.[^\\\"']*)[\\\"']?/i";
		preg_match_all($pattern, $data, $oembedLinks);
		if(isset($oembedLinks[1][0])) $oEmbedUrl = $oembedLinks[1][0];
	}
	
	// If found nothing at that point, use the oohembed.com service.
	if($oEmbedUrl == null) {
		$oEmbedUrl = "http://oohembed.com/oohembed/?url=".$url;
	}
	$param = "";
	foreach($params as $key => $value) $param .= "&".$key."=".$value;
	$ret = json_decode(curl_get($oEmbedUrl.$param."&format=json"));
	if($returnHtml) {
		if($ret->type == "video") {
			return $ret->html;
		} else {
			return "<img src=\"".$ret->url."\" width=\"".$ret->width."\" height=\"".$ret->height."\" />";
		}
	} else {
		return $ret;
	}
	
}

以上是关于PHP 透过oEmbed的主要内容,如果未能解决你的问题,请参考以下文章

php 创世纪档案描述oEmbed Shortcode支持

PHP 创建简单的基于oEmbed的WordPress短代码

php 将包装器div添加到oEmbed WordPress对象

php 将youtube缩略图和网址拉出ACF oEmbed字段以供使用

php 将youtube缩略图和网址拉出ACF oEmbed字段以供使用

php 将一些参数过滤到WordPress YouTube oEmbed请求中。启用适度品牌,隐藏YouTube徽标。删除视频标题