SOFTELメモ Developer's blog

会社概要 ブログ 調査依頼 採用情報 ...
てるてる動画

【php】Google Url Shortener API を file_get_contents()で

問題

Googleの短縮URLのAPIをphpから使いたい。 簡単?

答え

file_get_contents()で十分。 cURLなんて使わなくて大丈夫。

ドキュメントはこちらを参照 http://code.google.com/intl/ja/apis/urlshortener/

こんなリクエストを送りなさいと書いてある。

POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json

{"longUrl": "http://www.google.com/"}

そのようにしてみる。

<?php
$url = 'https://www.googleapis.com/urlshortener/v1/url'; //?key=xxxxxxx(あなたのAPIキー)
$data = '{"longUrl": "https://www.softel.co.jp/"}';
$options = array(
    'http' => array(
        'method' => 'POST',
        'header' => array(
            "Content-type: application/json",
            "Content-Length: " . strlen($data),
        ),
        'content' => $data
    )
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

//GoogleからのレスポンスはJSON形式
$r = json_decode($response);
var_dump($r);

結果

object(stdClass)#1 (3) {
  ["kind"]=>
  string(16) "urlshortener#url"
  ["id"]=>
  string(19) "http://goo.gl/iaeWH"
  ["longUrl"]=>
  string(24) "https://www.softel.co.jp/"
}

いつものPOSTリクエストのときのように、うっかり 'header' => "Content-type: application/x-www-form-urlencoded" と書いてしまうと、
PHP Warning: file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request と返されるので注意。

「API Keyの使用を強く推奨する」と書いてあるので、$url の後ろに ?key=xxxxxxxxx(あなたのAPIキー) をつけておいた方が、たぶんよいでしょう。

関連するメモ

コメント(2)

ひさっちの日記 » Blog Archive » Google URL Shortener APIのメモ 2011年4月2日 20:41

[…] <参考にさせていただいたところ> 【php】Google Url Shortener API を file_get_contents()で at softelメモ https://www.softel.co.jp/blogs/tech/archives/2323 […]

のりお 2011年7月25日 18:37

ググって出てくるcurlやソケットを使ったサンプルで取得できなかったので諦めかけていたところ、
こちらのサンプルを試してみたら1発で動きました。
勉強になりました。
ありがとうございます。