PHPプログラムに関する各種メモ書き

Googleの短縮URLサービスAPI goo.gl をPHPから使用する

Googleの短縮URLサービス goo.gl をPHPから使用するには以下のようなコードで実現できます。

1. APIキー( api_key )を取得する

https://code.google.com/apis/console/

ここから取得できます

2. 以下のPHPコードで実現できます( $api_key に取得したキーをセットすること )

function get_tiny_url($long_url=''){
	$api_url = 'https://www.googleapis.com/urlshortener/v1/url';
	$api_key = 'XXXXXXXXXXX';
	$curl = curl_init("$api_url?key=$api_key");
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, '{"longUrl":"' . $long_url . '"}');
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$res = curl_exec($curl);
	curl_close($curl);
	$json = json_decode($res);
	$tiny_url = $json->id;
	return $tiny_url;
}

使い方

$long_url = 'http://xxxx.xxxx.xxx.com/xxxxxxxxxxxxxx.html';
$tiny_url = get_tiny_url($long_url);

関連エントリー

No.781
04/04 17:46

edit

API
URL