Home  >  Article  >  php教程  >  调用新浪微博短址API代码

调用新浪微博短址API代码

PHP中文网
PHP中文网Original
2016-05-25 17:06:201064browse

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;
}
?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:IP2Long和Long2IP函数的PHP实现Next article:CURL封装类