bit.lyから短縮URLを取得する(シンプルバージョン)

アカウント登録する

http://bit.ly/
クリック回数などの解析機能のおまけ付きです。

PHPコード

$bitlyid = '****';               #発行されたID
$apikey = 'xxxxx';               #発行されたKEY
$url = "http://www.sample.net/"; #短縮したいURL


$long_url = htmlspecialchars($url, ENT_QUOTES);
$req = "http://api.bit.ly/shorten?login=$bitlyid&apiKey=$apikey&version=2.0.1&longUrl=".$long_url;

$contents = file_get_contents($req);
if(isset($contents)) {
	$data = json_decode($contents, true);
}

$shot_url = $data['results'][$long_url]['shortUrl'];


返却されるデータ構造体

array(4) { 
	["errorCode"]=> int(0) 
	["errorMessage"]=> string(0) "" 
	["results"]=> array(1) 
	{ ["<SEND LONG URL>"]=> array(5) 
		{ ["hash"]=> string(6) "czJsUY" 
			["shortCNAMEUrl"]=> string(20) "http://bit.ly/aC6rmQ" 
			["shortKeywordUrl"]=> string(0) "" 
			["shortUrl"]=> string(20) "http://bit.ly/aC6rmQ" 
			["userHash"]=> string(6) "aC6rmQ" 
		} 
	} 
	["statusCode"]=> string(2) "OK" 
}
ちなみに複数のやりとりも出来るようです。

http://tokuna.blog40.fc2.com/blog-entry-1945.html