首頁  >  文章  >  php教程  >  调用新浪微博短址API代码

调用新浪微博短址API代码

PHP中文网
PHP中文网原創
2016-05-25 17:06:201064瀏覽

php代码

<?php
$backurl="";
if (isset($_GET[&#39;type&#39;])){
	$type=$_GET[&#39;type&#39;];
	switch (trim($type))
	{
	case 1:
		if (isset($_GET[&#39;url&#39;])){
			$backurl=shorturl(urlencode($_GET[&#39;url&#39;]));  //注意必须经过urlencode
		}
		else{
			$backurl="error0";
		}
		break;
	case 2:
		if (isset($_GET[&#39;url&#39;])){
			$backurl=expandurl($_GET[&#39;url&#39;]);
		}
		else{
			$backurl="error1";
		}
		break;
	default:
		$backurl="error2";
	}
}
echo $backurl;

function shortenSinaUrl($long_url){
	$apiKey=&#39;xxxxxxxxx&#39;;    //请替换成你的APPID
	$apiUrl=&#39;https://api.weibo.com/2/short_url/shorten.json?source=&#39;.$apiKey.&#39;&url_long=&#39;.$long_url;
	$curlObj = curl_init();
	curl_setopt($curlObj, CURLOPT_URL, $apiUrl);
	curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curlObj, CURLOPT_HEADER, 0);
	curl_setopt($curlObj, CURLOPT_HTTPHEADER, array(&#39;Content-type:application/json&#39;));
	$response = curl_exec($curlObj);
	curl_close($curlObj);
	$json = json_decode($response);
	return $json->urls[0]->url_short;
}

function expandSinaUrl($short_url){
	$apiKey=&#39;xxxxxxxxx&#39;;    //请替换成你的APPID
	$apiUrl=&#39;https://api.weibo.com/2/short_url/expand.json?source=&#39;.$apiKey.&#39;&url_short=&#39;.$short_url;
	$curlObj = curl_init();
	curl_setopt($curlObj, CURLOPT_URL, $apiUrl);
	curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curlObj, CURLOPT_HEADER, 0);
	curl_setopt($curlObj, CURLOPT_HTTPHEADER, array(&#39;Content-type:application/json&#39;));
	$response = curl_exec($curlObj);
	curl_close($curlObj);
	$json = json_decode($response);
	return $json->urls[0]->url_long;
}


function shorturl($long_url){
	$apiKey=&#39;xxxxxxxxx&#39;;    //请替换成你的APPID
	$apiUrl=&#39;https://api.weibo.com/2/short_url/shorten.json?source=&#39;.$apiKey.&#39;&url_long=&#39;.$long_url;
	$response = file_get_contents($apiUrl);
	$json = json_decode($response);
	return $json->urls[0]->url_short;
}

function expandurl($short_url){
	$apiKey=&#39;xxxxxxxxx&#39;;    //请替换成你的APPID
	$apiUrl=&#39;https://api.weibo.com/2/short_url/expand.json?source=&#39;.$apiKey.&#39;&url_short=&#39;.$short_url;
	$response = file_get_contents($apiUrl);
	$json = json_decode($response);
	return $json->urls[0]->url_long;
}
?>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn