Display Flickr images using the API with PHP and cURL
Working on a small project whereby I need to tap into my clients Flickr account and display the images on his site. He wants them to loop through with jQuery but I will not showcase that code but will show the initial code to load in 5 images from Flickr and hold them in an array for later use.
First is the class code (flickr.cls.php):
- class Flickr
- {
- public function __construct($username = null, $user_id = null, $api_key = null)
- {
- $this->Username = $username;
- $this->Api_key = $api_key;
- $this->User_id = $user_id;
- $this->Response = array();
- $this->Timeout = 5;
- }
- public function getImages($count)
- {
- $url = 'http://api.flickr.com/services/rest/?api_key=' . urlencode($this->Api_key) . '&method=flickr.photos.search&user_id='.$this->User_id.'&per_page=' . urlencode($count);
- //echo $url;
- return $this->fetch($url);
- }
- public function fetch($url,$post = false)
- {
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_NOBODY, 0);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_USERAGENT, 'Flickr PHP Class by PHPology');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_TIMEOUT, $this->Timeout);
- $output = curl_exec($ch);
- $this->Response = curl_getinfo($ch);
- curl_close($ch);
- if((int)$this->Response['http_code'] == 200) {
- return new SimpleXMLElement($output);
- }
- else {
- return false;
- }
- }
- }
Next is the code to pull in the relevant images based on the Flickr user_id and API key:
require("services/models/flickr.cls.php"); $flickr = new Flickr('USER_ID', 'USER_ID', 'API-KEY'); $images = $flickr->getImages(5); $flickr_array = array(); $i = 0; if(count($images->photos->photo) > 0) { foreach($images->photos->photo as $photo) { $flickr_array[$i]['image_href'] = "http://flickr.com/photos/".$flickr->Username."/".$photo->attributes()->id.""; $flickr_array[$i]['image_path'] = "http://farm". $photo->attributes()->farm.".static.flickr.com/".$photo->attributes()->server."/" .$photo->attributes()->id."_".$photo->attributes()->secret."_n.jpg"; $i++; } } print_r($flickr_array);
You can now loop through $flickr_array where you need.
You can change the image size that you require also (currently I am pulling in "_n") but you can use this as a good resource to display the size you need: http://www.flickr.com/services/api/flickr.photos.getSizes.html
In an ideal world, you would want to cache this some how as retrieving data from Flickr on every page call would be slightly slow.