最近剛好有用到Flickr API
來做個紀錄以免自己以後忘了
首先你必須有一組Flicker帳號…廢話…
然後在這裡 http://www.flickr.com/services/apps/create/apply/ 申請一個API Key
接下來就可以開始呼叫API了
所有API的用法可以參考 http://www.flickr.com/services/api/
下面讓我來舉個例子
首先在寫程式之前可以先做個小測試確定你的KEY跟API是活著的
直接在網頁輸入以下網址測試 http://www.flickr.com/services/rest/?method=flickr.photosets.getInfo&format=php_serial&photoset_id=相片集的編號&api_key=我的APIKEY
送出之後網頁就會把API呼叫的值回傳如下
a:2:{s:8:"photoset";a:16:{s:2:"id";s:17:"72157602138543609";s:5:"owner";s:12:"35663569@N00";s:7:"primary";s:10:"1430638617";s:6:"secret";s:10:"84ec9d1936";s:6:"server";s:4:"1063";s:4:"farm";d:2;s:6:"photos";i:135;s:11:"count_views";s:3:"542";s:14:"count_comments";s:1:"0";s:12:"count_photos";s:3:"135";s:12:"count_videos";i:0;s:5:"title";a:1:{s:8:"_content";s:22:"PARKⅡ‧映相巴黎";}s:11:"description";a:1:{s:8:"_content";s:0:"";}s:11:"can_comment";i:0;s:11:"date_create";s:10:"1190610982";s:11:"date_update";s:10:"1316530838";}s:4:"stat";s:2:"ok";}
這是JSON的結構
基本上回你很長一串就是你語法沒填錯了,或是你也可以檢查最後面的stat=’OK’
像我用PHP的話可以用 unserialize() 來把JSON解開成陣列
這樣就可以方便的抓到傳回的元素了
設定上相片集設成公開就可以抓到了
另外別忘了Flicker的條款規定頁面上要放回到Flickr的連結
以下的程式是用來抓Flickr相片集的封面
可以簡單的參考一下
$link 是相片集的連結
function getflckrset($link)
{
global $FLICKRKEY;
$setid = substr($link,strpos($link,’sets/’)+5);
$setid = str_replace(‘/’,",$setid);
//get photo
$params = array(
‘api_key’ => $FLICKRKEY,
‘method’ => ‘flickr.photosets.getPhotos’,
‘photoset_id’ => $setid ,
‘format’ => ‘php_serial’
);
$encoded_params = array();
foreach ($params as $k => $v)
$encoded_params[] = urlencode($k).’=’.urlencode($v);
$url = “http://api.flickr.com/services/rest/?".implode(‘&’, $encoded_params);
$rsp = file_get_contents($url);
$rsp_obj = unserialize($rsp); //parser JSON formate
$imgname = $rsp_obj[‘photoset’][‘photo’][0][‘id’].’_’.$rsp_obj[‘photoset’][‘photo’][0][‘secret’].’.jpg’;
//get server
$params = array(
‘api_key’ => $FLICKRKEY,
‘method’ => ‘flickr.photosets.getInfo’,
‘photoset_id’ => $setid ,
‘format’ => ‘php_serial’
);
$encoded_params = array();
foreach ($params as $k => $v)
$encoded_params[] = urlencode($k).’=’.urlencode($v);
$url = “http://api.flickr.com/services/rest/?".implode(‘&’, $encoded_params);
$rsp = file_get_contents($url);
$rsp_obj = unserialize($rsp);
$farm = $rsp_obj[‘photoset’][‘farm’];
$server = $rsp_obj[‘photoset’][‘server’];
$imgurl = ‘http://farm’.$farm.’.staticflickr.com/’.$server.’/’.$imgname;
return $imgurl;
}