goo.glをPHPで使う

  • 2012.08.12
  • 2013.07.12
  • Web

PHPでgoo.glの短縮URLを作成する方法

 

自分用メモ


<?php
$url = 'https://nsdev.jp';
$api_key = 'APIキー';

$json_data = ‘{“longUrl”: “‘. $url. ‘”}’;

$header = ‘Content-Type: application/json’. “\r\n”;
$header .= ‘Content-Length: ‘. strlen($json_data);

$context = array(
‘http’ => array(
‘method’ => ‘POST’,
‘header’ => $header,
‘content’ => $json_data
)
);

$json = file_get_contents(‘https://www.googleapis.com/urlshortener/v1/url?key=’.$api_key, FALSE, stream_context_create($context));

$obj = json_decode($json);
echo $obj->{‘id’};
?>