Skip to content

Instantly share code, notes, and snippets.

@manastungare
Created May 7, 2012 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manastungare/2625142 to your computer and use it in GitHub Desktop.
Save manastungare/2625142 to your computer and use it in GitHub Desktop.
Twitter Badge
<?php
// Example: Get a single tweet.
$status = getTwitterStatus("manas");
echo($status[0]['message'] . ' - ' . $status[0]['time']);
// Example: Get multiple tweets.
$statuses = getTwitterStatus("manas", 100);
foreach ($statuses as $status) {
echo($status['message'] . ' - ' . $status['time']);
}
/**
* A simple Twitter status display script.
* Useful as a status badge for JavaScript non-compliant browsers, where the
* insertion of the status message must be performed on the server.
*
* @author Manas Tungare, manas@tungare.name
* @version 1.1
* @copyright Manas Tungare, 2007 onwards.
* @license Creative Commons Attribution ShareAlike 3.0.
*/
function getTwitterStatus($twitterUser, $howMany = 1) {
$url = sprintf("http://twitter.com/statuses/user_timeline/%s.xml?count=%d",
$twitterUser, $howMany);
$parsed = new SimpleXMLElement(file_get_contents($url));
$tweets = array();
foreach($parsed->status as $status) {
$message = preg_replace("/http:\/\/(.*?)\/[^ ]*/", '<a href="\\0">\\0</a>',
$status->text);
$time = niceTime(strtotime(str_replace("+0000", "", $status->created_at)));
$tweets[] = array('message' => $message, 'time' => $time);
}
return $tweets;
}
/**
* Formats a timestamp nicely with an adaptive "x units of time ago" message.
* Based on the original Twitter JavaScript badge. Only handles past dates.
* @return string Nicely-formatted message for the timestamp.
* @param $time Output of strtotime() on your choice of timestamp.
*/
function niceTime($time) {
$delta = time() - $time;
if ($delta < 60) {
return 'less than a minute ago.';
} else if ($delta < 120) {
return 'about a minute ago.';
} else if ($delta < (45 * 60)) {
return floor($delta / 60) . ' minutes ago.';
} else if ($delta < (90 * 60)) {
return 'about an hour ago.';
} else if ($delta < (24 * 60 * 60)) {
return 'about ' . floor($delta / 3600) . ' hours ago.';
} else if ($delta < (48 * 60 * 60)) {
return '1 day ago.';
} else {
return floor($delta / 86400) . ' days ago.';
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment