Use PHP to Display Your Last Tweet from Twitter

This week I was building a website for a church where they wanted the last tweet from the minister to appear on the home page. It sounds like the kind of thing that everyone does and rather than reinvent the wheel I thought I'd google for a little script. I found a lot of sites with scripts but they mostly boiled down to the same 3 or 4 scripts - and none of them worked.

So no choice - write my own. To use it you will need to substitue your RSS url for the one in the variable $myFile on line 3. You will also need to substitute the first 4 letters of your twitter username for the word ‘John’ on line 10.

On line 18 change the phrase between the quotes to whatever you want yours to say (if the feed stops working) and you are away. It displays the first 70 characters followed by … To change this change the number 70 on line 14 to whatever number of characters you want.

Here it is - free to use, and in return I would appreciate a link for my troubles. Please link to ‘http://www.webtechnologyqueensland.com/web-design’ and use the word ‘web design’ in the anchor text. 

<?php

$myFile = "http://twitter.com/statuses/user_timeline/251836287.rss";
 $fh = fopen($myFile, 'r');
 $status = fread($fh, 1000);
 fclose($fh);
//echo $status;

$newstatus = trim(substr($status, 546));
if (substr($newstatus, 0, 4) == 'John')

{
$newstatus2 = trim(substr($status, 557));
echo substr($newstatus2, 0, 70); 
echo “…”;

}
else
{
echo "Follow JohnKAlley on Twitter, get tweets from Peace Apostolic Community.";
}

?>

IMPORTANT NOTE: This script uses a php file function to open a read the rss feed file. It then truncates (chops) off everything up to the first feed. You may need to adjust the numbers in the trim(substr($status section to chop off the right amount of characters. This happens twice. The first time you chop off everything up to the username – so you can validate the first 4 letters of the username. The second time you chop the username off too. If you don’t want to chop the username off – simply remove the number 2 from both $newstatus2 variables and it will include the username. 

Add new comment

Full HTML

  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.

Filtered HTML

  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.