I am periodically getting tweets, formatting them, and storing them into the database. Now the line of code I use for this is an awful lot. I was wondering if this could be improved.
// This is the wordpress way of getting a json object
// Wordpress will determine how the data is going to
// be fetched looking at what PHP functions are
// enabled for the user, wget, curl, etc.
$json_body = wp_remote_retrieve_body(
wp_remote_get(
'http://twitter.com/statuses/user_timeline/'.$options['username'].'.json?count='.$options['count'] ) );
$tweet = json_decode( $json_body, true );
for( $i = 0; $i < $options['count']; $i++ ){
$latestTweet = htmlentities($tweet[$i]['text'], ENT_QUOTES);
$latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
$latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
// This array $data will be stored to the DB
// I will use the *serialize()* function for this.
$data[] = array( 'text' => $latestTweet, 'time' => timespan( $tweet[$i]['created_at'] ) );
}
function timespan( $a )
{
//get current timestampt
$b = strtotime("now");
//get timestamp when tweet created
$c = strtotime($a);
//get difference
$d = $b - $c;
//calculate different time values
$minute = 60;
$hour = $minute * 60;
$day = $hour * 24;
$week = $day * 7;
if(is_numeric($d) && $d > 0) {
//if less then 3 seconds
if($d < 3) return "right now";
//if less then minute
if($d < $minute) return floor($d) . " seconds ago";
//if less then 2 minutes
if($d < $minute * 2) return "about 1 minute ago";
//if less then hour
if($d < $hour) return floor($d / $minute) . " minutes ago";
//if less then 2 hours
if($d < $hour * 2) return "about 1 hour ago";
//if less then day
if($d < $day) return floor($d / $hour) . " hours ago";
//if more then day, but less then 2 days
if($d > $day && $d < $day * 2) return "yesterday";
//if less then year
if($d < $day * 365) return floor($d / $day) . " days ago";
//else return more than a year
return "over a year ago";
}
}