Flickr是陋室博客使用的外链相册,之前遇到过许多问题,今天把调试好的调用图片的php函数贴出来:
$params = array(
'api_key' => 'api_key_code', //API接口密钥
'method' => 'flickr.people.getPublicPhotos',
'user_id' => '55812899@N04', //用户ID,这里是我的
'format' => 'php_serial',
'per_page' => '200', //图片显示数量
'page' => '1',
);
$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); //create an multi-dimension array with data
//如果完成xml解析则进行下一步
if ($rsp_obj['stat'] == 'ok'){
foreach ($rsp_obj['photos']['photo'] as $photo){
if ($photo['farm']==6){ //使用if过滤掉被墙的图片
$photo['m_url'] = 'http://farm'.$photo['farm'].'.static.flickr.com/'.$photo['server'].'/'.$photo['id'].'_'.$photo['secret'].'_m.jpg';
$photo['m_urz'] = 'http://farm'.$photo['farm'].'.static.flickr.com/'.$photo['server'].'/'.$photo['id'].'_'.$photo['secret'].'_z.jpg';
echo '<div class="item"><a href="'.$photo['m_urz'].'" rel="lightbox[roadtrip]"><img src="'.$photo['m_url'].'" alt="陋室图片"/></a></div>';
}
}
}else{
echo "获取失败!";
}
还有另外一种方法,与上面类似,只是调用xml稍有不同代码看起来更好理解:
$url = 'http://api.flickr.com/services/rest/'; // 请求的URL地址
$params = '?method=flickr.people.getPublicPhotos' . // method指明Flickr API所提供的某个方法
'&api_key=1233434' . // Flickr分配的key
'&user_id=55812899@N04' . // 用户ID
'&per_page=200'. // 单页数量
'&page=1'; // 页数
//生成的URL
//http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=yourkey&user_id=55812899@N04&per_page=2$page=1
//如果把改URL黏贴到浏览器的地址栏里,同样可以得到XML文件,以上api_key后面yourkey需要替换
//
//关于flickr尺寸
//s小方
//m小原始
//t中原始
//z大原始
$contents = file_get_contents($url . $params);
$xml = new SimpleXMLElement($contents); // 解析XML文件
foreach ($xml->photos->photo as $value) {
if ($value['farm']==6){
$src = 'http://farm' . $value['farm'] . ".static.flickr.com/" .
$value['server'] . '/' . $value['id'] . '_' . $value['secret'] . '_s.jpg'; // _s用来控制显示图片的大小
$srv = 'http://farm' . $value['farm'] . ".static.flickr.com/" .
$value['server'] . '/' . $value['id'] . '_' . $value['secret'] . '_m.jpg'; // _m用来控制显示图片的大小
$srt = $value['title'];
echo "<div class=\"item\"><a href=\"$srv\" rel=\"lightbox[roadtrip]\" title=\"$srt\"><img src=\"$src\" alt=\"file\"/></a></div>";
}
// $b = "<div class=\"item\"><a href=\"$srv\" rel=\"lightbox[roadtrip]\"><img src=\"$src\" alt=\"file\"/></a></div>";
// file_put_contents($path,$b,FILE_APPEND); //这段是写入html文件的,不过暂时有bug
}
演示页面:
附录:
Flickr接口函数文档http://www.flickr.com/services/api/flickr.photos.search.html