新浪t.cn短网址接口(PHP)

使用前要先去申请API-KEY,或使用oAuth进行认证。
将长网址变为短网址的方法:

<?php
function shortenSinaUrl($long_url){
$apiKey=’API-KEY’;
$apiUrl=’http://api.t.sina.com.cn/short_url/shorten.json?source=’.$apiKey.’&url_long=’.$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(‘Content-type:application/json’));
$response = curl_exec($curlObj);
curl_close($curlObj);
$json = json_decode($response);
return $json[0]->url_short;
}
?>

将短网址还原成长网址的方法:

<?php
function expandSinaUrl($short_url){
$apiKey=’API-KEY’;
$apiUrl=’http://api.t.sina.com.cn/short_url/expand.json?source=’.$apiKey.’&url_short=’.$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(‘Content-type:application/json’));
$response = curl_exec($curlObj);
curl_close($curlObj);
$json = json_decode($response);
return $json[0]->url_long;
}
?>

更多具体使用方法,请参见:http://open.t.sina.com.cn/wiki/index.php/Short_url/expand

原文地址:http://www.biaodianfu.com/sina-shortener-url-api-php.html

Google短网址API(PHP版)

在使用前,请先到这里申请API Key:http://code.google.com/apis/console/
短网址的生成需要使用POST提交数据,所以使用了curl,短网址的还原可以直接使用file_get_contents()函数。不过为了统一,我也使用了curl来处理,现在感觉curl真的是非常有用,等有空对curl还要加大学习哈。

<?php
function shortenGoogleUrl($long_url){
$apiKey = ‘API-KEY’; //Get API key from : http://code.google.com/apis/console/
$postData = array(‘longUrl’ => $long_url, ‘key’ => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, ‘https://www.googleapis.com/urlshortener/v1/url’);
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(‘Content-type:application/json’));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
curl_close($curlObj);
$json = json_decode($response);
return $json->id;
}
?>
<?php
function expandGoogleUrl($short_url){
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, ‘https://www.googleapis.com/urlshortener/v1/url?shortUrl=’.$short_url);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curlObj);
curl_close($curlObj);
$json = json_decode($response);
return $json->longUrl;
}
?>

原文地址:http://www.biaodianfu.com/php-google-urlshortener-api.html