Display photos from Tumblr (using JSON method)
This snippet pull the data from Tumblr, a microblog service and display them on Drupal block. There are 3 ways to aggregate data from any Tumblr blog:
- RSS feed - via http://(username).tumblr.com/rss
- XML feed - via http://(username).tumblr.com/api/read
- JSON - via http://(username).tumblr.com/api/read/json
(See Tumblr API page for details)
This snippet choose the JSON method. All you need is PHP json module enabled (come as default bundled with PHP 5.2). This example will choose only photo type from Tumblr but since you get every JSON elements in array, you can change by your own.
<?php
// don't forget to change 'username' to your actual tumblr name
$request = 'http://(username).tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
// Tumblr JSON doesn't come in standard form, some str replace needed
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
// parameter 'true' is necessary for output as PHP array
$value = json_decode($input, true);
$content = $value['posts'];
// the number of items you want to display
$item = 5;
// Tumblr provides various photo size, this case will choose the 75x75 square one
$type = 'photo-url-75';
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
echo '<a href="' . $content[$i]['url'] . '"><img src="' . $content[$i][$type] . '" width="75" hspace="3" alt="' . $content[$i]['photo-caption'] . '" title="' . $content[$i]['photo-caption'] . '" /></a>';
}
}
?>