あっきぃ日誌

鉄道ブログのような技術系ブログのようななにか

PHPでbit.lyのAPIをたたく

このエントリを書いてる時点で最新のバージョン3.0準拠にしてます。
ApiDocumentation - bitly-api - bitly REST API method documentation - API Libraries and Documentation for bitly - Google Project Hosting

<?php
	// bit.lyで無償で取得できる
	$username = 'ユーザ名';
	$apikey   = 'APIキー';

	// formatはxmlも選べる
	$request  = 'http://api.bit.ly/v3/shorten?login=' . $username .
				'&apiKey=' . $apikey . '&uri=' . $url . '&format=json';

	try {
		$req = new HTTP_Request2($request);
		$response = $req->send();
		$json = json_decode($response->getBody());
		if ($json->status_code != 200) { print "failed!"; }
		$link = $json->data->url;
	} catch (HTTP_Request2_Exception $e) {
		die($e->getMessage());
	}
	print $link;
?>

上記のサンプルはURLが複数あることを想定してませんが、「&uri=」を書き連ねるだけで良いようなので、ソレをするコード、配列かどうか(URLが1個か複数か)の判別をするコード、配列で返すコードなどを書き加えるだけで応用できそうな気がします。