Archive for the ‘ Cache ’ Tag

Cache twitter feeds into a file in PHP (search api request)

  • Articles written so far : 99

In my previous post, i explained how to cache feeds directly in json format and show them in your web page from the cache file. In this post, i will show you how to get feeds from search api with having multiple usernames and store them in a file. Credit goes to Scott for his work back in 2009, i have modified the script to my taste and clean it a little bit.

1st of all create a directory named cache (better in the same directory where the script will be saved). Change the permissions to write into the directory. Time interval i set to 10 minutes, you can change it in the script. Now copy and paste the following script and save it as anyname.php. You can modify it to your taste as you wish..

<style>
#twitter {
padding:5px 15px;
line-height:1.6em;
}
#twitter ul li{margin:10px 0; background:none; padding:0}
#twitter span a {color:#35d0ff}
#twitter a:link {color:#35d0ff; font-style:italic}
#twitter a:visited {color:#35d0ff; font-style:italic}
</style>

<?php
define("SECOND", 1);
define("MINUTE", 60 * SECOND);
define("HOUR", 60 * MINUTE);
define("DAY", 24 * HOUR);
define("MONTH", 30 * DAY);
function relative_time($time)
{
$delta = strtotime('now') - $time;
if ($delta < 2 * MINUTE) {
return "1 min ago";
}
if ($delta < 59 * MINUTE) {
return floor($delta / MINUTE) . " min ago";
}
if ($delta < 90 * MINUTE) {
return "1 hour ago";
}
if ($delta < 24 * HOUR) {
return floor($delta / HOUR) . " hours ago";
}
if ($delta < 48 * HOUR) {
return "yesterday";
}
if ($delta < 30 * DAY) {
return floor($delta / DAY) . " days ago";
}
if ($delta < 12 * MONTH) {
$months = floor($delta / DAY / 30);
return $months <= 1 ? "1 month ago" : $months . " months ago";
} else {
$years = floor($delta / DAY / 365);
return $years <= 1 ? "1 year ago" : $years . " years ago";
}
}

function parse_twitter_cache_feed($username, $limit) {
$username = str_replace(",", "+OR+", $username); // for multiple usernames
$file = "twitter-tweets-cache";
$cache_file = dirname(__FILE__).'/cache/' . $file; // file name and path
$feed = "http://search.twitter.com/search.atom?rpp=".$limit."&q=".$username;
$last = filemtime($cache_file); // get file modification time
$now = time();
$interval = 600; // time in seconds
$get_time_lapse = $now - $last;
if ( $get_time_lapse  > $interval ) { // check for the time since we wrote to the file
$ch = curl_init();
$timeout = 0; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $feed);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$cache_ = curl_exec($ch);
curl_close($ch);
ob_start(); // turn on the output buffering
$fp = fopen($cache_file, 'wb'); // opens for writing only or will creat it's not there
fwrite($fp, $cache_); // writes to the file what was grabbed from the previouse function
fclose($fp); // closes
ob_end_flush(); // finishes and flushes the output buffer
}
else {
//echo "Do nothing dude";
}
$rss = file_get_contents($cache_file);
$feed = str_replace("&amp;", "&", $rss);
$feed = str_replace("&lt;", "<", $feed);
$feed = str_replace("&gt;", ">", $feed);
$feed = str_replace("”", '"', $feed);
$feed = str_replace("“", '"', $feed);
$feed = str_replace("’", "'", $feed);
$clean = explode("<entry>", $feed);
$clean = str_replace("&quot;", "\"", $clean);
$clean = str_replace("&apos;", "'", $clean);
$amount = count($clean) - 1;
if ($amount) { // are there any tweets?
for ($i = 1; $i <= $amount; $i++) {
$entry_close = explode("</entry>", $clean[$i]);
$clean_content_1 = explode("<content type=\"html\">", $entry_close[0]);
$clean_content = explode("</content>", $clean_content_1[1]);
$clean_name_2 = explode("<name>", $entry_close[0]);
$clean_name_1 = explode("(", $clean_name_2[1]);
$clean_name = explode(")</name>", $clean_name_1[1]);
$clean_user = explode(" (", $clean_name_2[1]);
$clean_lower_user = strtolower($clean_user[0]);
$clean_uri_1 = explode("<uri>", $entry_close[0]);
$clean_uri = explode("</uri>", $clean_uri_1[1]);
$clean_time_1 = explode("<published>", $entry_close[0]);
$clean_time = explode("</published>", $clean_time_1[1]);
$unix_time = strtotime($clean_time[0]);
$pretty_time = relative_time($unix_time);
?>
<div id='twitter'>
<?php echo $clean_content[0]; ?>&nbsp;&nbsp;
<?php echo $pretty_time; ?>
</div>
<?php
}
} else { // if there aren't any tweets
?>
<div id='twitter'>
No recent tweets...
</div>

<?php
}
}

parse_twitter_cache_feed("username1,username2", 5);
?>

Just run this script in the browser, few changes you might need by changing usernames, one thing more i would like to mention is if you want one user feeds, just input one username like:

parse_twitter_cache_feed(“username”, 5);

And that’s it.

Cache twitter feeds into a file and show it from the file in PHP (direct request)

  • Articles written so far : 99

Showing feeds directly from twitter will some time(most of the time) get you blank page or empty tweets. Why?, because the direct request to twitter api is limited to 150 requests per hour. We can use search api, will discuss this in some other post.

Lets get to work, 1st of all create a directory named cache any where where you will save your script feeds file(better in the same directory where the script will be saved). Change the permissions to write into the directory. Now copy and paste the following script and save it.

<style>
#twitter {
padding:5px 15px;
line-height:1.6em;
}
#twitter ul li{margin:10px 0; background:none; padding:0}
#twitter span a {color:#35d0ff}
#twitter a:link {color:#35d0ff; font-style:italic}
#twitter a:visited {color:#35d0ff; font-style:italic}
</style>

<?php
error_reporting(~E_NOTICE);
define("SECOND", 1);
define("MINUTE", 60 * SECOND);
define("HOUR", 60 * MINUTE);
define("DAY", 24 * HOUR);
define("MONTH", 30 * DAY);
function relative_time($time)
{
$delta = strtotime('now') - $time;
if ($delta < 2 * MINUTE) {
return "1 min ago";
}
if ($delta < 59 * MINUTE) {
return floor($delta / MINUTE) . " min ago";
}
if ($delta < 90 * MINUTE) {
return "1 hour ago";
}
if ($delta < 24 * HOUR) {
return floor($delta / HOUR) . " hours ago";
}
if ($delta < 48 * HOUR) {
return "yesterday";
}
if ($delta < 30 * DAY) {
return floor($delta / DAY) . " days ago";
}
if ($delta < 12 * MONTH) {
$months = floor($delta / DAY / 30);
return $months <= 1 ? "1 month ago" : $months . " months ago";
} else {
$years = floor($delta / DAY / 365);
return $years <= 1 ? "1 year ago" : $years . " years ago";
}
}

function parse_twitter_cache_feed($username, $limit) {
$username_for_file = str_replace(" ", "-", $username); // remove spaces from username
$cache_file = dirname(__FILE__).'/cache/' . $username_for_file . '-twitter-cache.json'; // file name and path
if(!file_exists($cache_file)) { // check for file, if not exists ceate one
$FileHandle = fopen($cache_file, 'wb');
fclose($FileHandle);
}
$last = filemtime($cache_file); // get file modification time
$now = time();
$interval = 3600; // time in seconds
$get_time_lapse = $now - $last;
if ( $get_time_lapse  > $interval ) { // check for the time since we wrote to the file
$feed = "http://twitter.com/statuses/user_timeline/".$username.".json?count=".$limit;
$ch = curl_init();
$timeout = 0; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $feed);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$cache_ = curl_exec($ch);
curl_close($ch);
ob_start(); // turn on the output buffering
$fp = fopen($cache_file, 'w'); // opens for writing only
fwrite($fp, $cache_); // writes to the file
fclose($fp); // closes
ob_end_flush(); // finishes and flushes the output buffer
}
else {
//echo "Do nothing dude";
}
$json = file_get_contents($cache_file);
$json = json_decode($json, true);
if($json) {
$count = 4; // get 5 tweets
for ($i=0; $i <= $count; $i++){
//Assign feed to $feed
$feed = $json[$i]
1
;
$feed = str_replace("&amp;", "&", $feed);
$feed = str_replace("&lt;", "<", $feed);
$feed = str_replace("&gt;", ">", $feed);
$feed = str_replace("”", '"', $feed);
$feed = str_replace("“", '"', $feed);
$feed = str_replace("’", "'", $feed);
$feed = str_replace("&quot;", "\"", $feed);
$feed = str_replace("&apos;", "'", $feed);
$startat = stripos($feed, '@');
$numat = substr_count($feed, '@');
$numhash = substr_count($feed, '#');
$numhttp = substr_count($feed, 'http');
$feed = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", "<a href=\"\\0\" target='_blank'>\\0</a>", $feed);
$feed = preg_replace("(@([a-zA-Z0-9\_]+))", "<a href=\"http://www.twitter.com/\\1\" target='_blank'>\\0</a>", $feed);
$feed = preg_replace('/(^|\s)#(\w+)/', '\1<a href="http://search.twitter.com/search?q=%23\2" target="_blank">#\2</a>', $feed);
$unix_time = strtotime($json[$i][created_at]);
$sweet_time = relative_time($unix_time);
echo "<div id='twitter'>". $feed ."&nbsp;&nbsp;". $sweet_time ."</div>";
}
}
else { // if there aren't any tweets
echo "<div id='twitter'>No recent tweets...</div>";

}
}

parse_twitter_cache_feed("username", 5); // in username space, input ur username or screen name for twitter
?>

Script is well explained, but if you still need more explanation, use the comment form below and i will try my best to justify your question.