tetsunosukeのnotebook

tetsunosukeのメモです

Google URL ShortenerのAPIが公開されたので

PHPなんですけどちょろっと書いたのでメモ。

URLの短縮に関してのAPIドキュメントは下記。
http://code.google.com/intl/ja/apis/urlshortener/v1/getting_started.html#shorten

データとしてJSONをPOSTするらしい。

public static function getGoogleShortUrl($url)
{
    $ch = curl_init();
    curl_setopt ($ch,CURLOPT_URL,'https://www.googleapis.com/urlshortener/v1/url');
    curl_setopt ($ch,CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = '{"longUrl" : "' . $url . '"}';
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    $res = curl_exec($ch);
    $ar = json_decode($res);
    curl_close ($ch);
    return $ar->{'id'};
}