Skip to content

Instantly share code, notes, and snippets.

@iamkeir
Created December 28, 2010 23:38
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 iamkeir/757913 to your computer and use it in GitHub Desktop.
Save iamkeir/757913 to your computer and use it in GitHub Desktop.
Twitter feed parser
<?php
// TWEED: Twitter feed parser
function Tweed ($user, $limit = NULL) {
$tweedURL = 'http://search.twitter.com/search.atom?q=from:' . $user; // Twitter RSS feed URL
$tweedXML = simplexml_load_file($tweedURL); // Convert RSS to XML
$count = 0; // Set count
foreach ($tweedXML->entry as $entry) { // Loop through each XML entry
$count++;
$tweet = array();
$tweet['status'] = $entry->content;
$tweet['timestamp'] = $entry->published;
$tweet['link'] = $entry->link[0]['href'];
$twitterFeed['tweets'][] = $tweet; // Add to stack
if (isset($count) && $count >= $limit) {break;} // If loop count = limit, break
}
return $twitterFeed;
} // END TWEED
?>
<?php
// TIMESINCE: Works out the time since the entry post, takes an argument in unix time (seconds)
function TimeSince($original) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365, 'year'),
array(60 * 60 * 24 * 30, 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24, 'day'),
array(60 * 60, 'hour'),
array(60, 'min'),
array(1, 'sec'),
);
$today = time(); /* Current unix time */
$since = $today - strtotime($original);
// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
// add second item if its greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 '.$name2 : " $count2 {$name2}s";
}
}
return $print . ' ago';
} // END TIMESINCE
?>
<ol class="listTwitter">
<?php
// Output recent tweets
$username = 'iamkeir';
$limit = 5;
$twitterFeed = @Tweed($username, $limit);
?>
<? if(isset($twitterFeed['tweets'])) { ?>
<? foreach($twitterFeed['tweets'] as $tweet) { ?>
<li><?=$tweet['status']?>
<a class="timestamp" href="<?=$tweet['link']?>"><?=TimeSince($tweet['timestamp'])?></a>
</li>
<? } ?>
<? } else { ?>
<li class="noItems"><em>No tweets found...</em></li>
<? } ?>
</ol><!-- /.listTwitter -->
<p class="lnkTwitter"><a href="http://twitter.com/<?=$username?>">Follow @<?=$username?> on Twitter &raquo;</a></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment