Update: I’ve added a new chunk of code that will download and store your Twitter posts in a database, allowing you to do whatever the heck you want with them. After you’ve finished reading this, be sure to check that out as well.
I am not a fan of social networking or so-called lifestreaming. I think it’s a BS excuse to fiddle on your computer more. Instead of telling everyone where you are and what you’re doing, go out and meet some friends for a drink.
However I did find a practical use for Twitter in a recent issue of php|architect (Twitter as a Development Tool by Sam McCallum). The article discussed using Twitter as an automated logger, where a program would make posts to a Twitter account based on system actions (i.e. log in/out, create accounts, etc.).
I decided to turn the idea around a bit and use Twitter as an activity log to chronicle my development work on a new project. Think SVN log comments without the repository. The site itself is currently a simple placeholder page, so Twitter updates make an easy way to keep a website fresh while building out the service that will eventually reside there. It also engages the users that wind up looking at the site, letting them know that it might be something of interest to them. That’s to say nothing of any SEO or attention-grabbing effects that may result from having a Twitter stream.
Given the rabidity surrounding said scoial networking silliness, I thought that finding a suitable plug ‘n play solution to this would be easy. Surprisingly (or perhaps unsurprisingly) many of the Twitter scripts I found were plain garbage. The following code was put together by sifting through what I found and putting the best working bits together. So if this sounds interesting, or if you were also frustrated with the plethora of crappy Twitter code, here’s how you can easily display your Twitter updates on any site using PHP.
First, grab this function…
function twitter_status($twitter_id, $hyperlinks = true) {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($c, CURLOPT_TIMEOUT, 5);
$response = curl_exec($c);
$responseInfo = curl_getinfo($c);
curl_close($c);
if (intval($responseInfo['http_code']) == 200) {
if (class_exists('SimpleXMLElement')) {
$xml = new SimpleXMLElement($response);
return $xml;
} else {
return $response;
}
} else {
return false;
}
}
I’m not going to discuss the various cURL options here or how Twitter uses cURL, as its outside the scope of our discussion here. If you’re lost or curious, you can read up on the cURL library, cURL in PHP, and/or the Twitter API.
As its name implies, twitter_status() will connect to Twitter and grab the timeline for the Twitter account identified by the $twitter_id. The $twitter_id is a unique number assigned to every Twitter account. You can find yours by visiting your profile page and examining the RSS link at the bottom left of the page. The URL will look like this:
http://twitter.com/statuses/user_timeline/12345678.rss
That 8-digit number at the end is your ID. Grab it and pass it as the lone argument to twitter_status(). Note that, as long as your Twitter profile is public, you do not need to pass any credentials to retrieve a user timeline. The API makes this information available to anyone, anywhere. There are more options that can be accessed through the user_timeline() function, if you’re curious.
The next step is to actually use the returned data, which comes in one of two forms: a SimpleXML object, or a raw XML document. SimpleXML is preferred because it’s a PHP object, and allows you access to all the usual object manipulation. Very easy. SimpleXML was added to PHP starting with version 5. The PHP manual has all the necessary details on SimpleXML.
The following code example assumes you’re using SimpleXML. Here I am taking the first five results and putting them in an HTML list. I’ll include a link to view the profile, as well as an error message in case Twitter is suffering from one of its famous fail-whale spasms.
-
status as $key => $status) {
?>
- text; ?>
- more...
If you want to see this code in action, just check out the front page of Fwd:Vault, my new full-time startup. While you’re checking out the code in action, why don’t you follow along with me @fwdvault?
Build a slick Twitter feed on your site
- Display Twitter updates on your website
- Calculate dates and times in different timezones (translate Twitter timestamps)
- Parse URL’s in text, create links
- New Download and store Twitter posts in a MySQL table
thanks for the help.
can you tell me where this code goes?
i am using an xhtml template for blogger.
can i use this there and if not, how can i set it up on my own site?
Thanks a lot man. I’ve been looking for something like this for a while now…awesome snippet!
@greg: Since this is all PHP code, so you’ll need to be able to insert PHP code for this to work. I don’t have much blogger experience, however I’m fairly certain that blogger doesn’t allow PHP code editing. I could be wrong.
@Sajan: You’re welcome!
It works perfectly(: Thanks!
Glad it met your needs, Liz!
I’m not sure exactly how to implement this. where do i place function? in the body or do i need to make it a php include? can you show me an example of what this looks like in the source code?
The
twitter_status()function belongs somewhere in the PHP for your page; whether that gets there via aninclude()or placed directly on the page is completely up to you.In my earlier placeholder site, I just tossed the function at the bottom of the file. My new site uses a proper framework, so the function is now located in a separate function file. It doesn’t matter where it goes, as long as PHP can see and process it.
So useful! Thank you so much for this helpful post.
Amazing! 2 days of messing with other scripts that I found and then 10min with this one… WTF. Well done!
Glad it helped, Marc!
Like I mentioned in the article, the craze surrounding any technology can have an inverse effect on the quality of available tools. Twitter’s no exception: most of the code out there right now is plain crap, written by fans, not developers attempting to leverage it. As the fervor settles down, we’ll see polished tools and established code libraries take hold.
how about the date/time it was posted?
Jon, I made a follow-up post for precisely this topic:
http://frankkoehl.com/2008/11/easily-calculate-dates-and-times-in-different-timezones/
Hey, this code is just what i have been looking for! Unfortunately i cant seem to get it to work!
Ive got the javascript in its own file, being included into the page through the header, in a similar way to the css, and then the php coding inside the page where i want it to be displayed. But all i keep getting is “Fatal error: Call to undefined function twitter_status() in”
any help would be great,
cheers
Sounds like a PHP error, Damien. It’s looking for the
twitter_status()function laid out in the first code block. You have to include that in the PHP that loads your page.Could I enlist your assistance in putting together a page that collates a few client twitters on that page ( shows them off live from Twitter ). No PHP experience, OK with HTML, but lost. Can you help ?
thanks
John ( Au )
Hey Frank,
Ive tried having the js in a .js file and then including it on that page in the , ive put the js in the actual head instead of including it from a seperate file, and its been copied and pasted exactly from this site, with the only alterations being the link given in the code so its linked to my twitter page, and then the twitter number code to read my page. I just cant seem to get it to read that function. Both sets of codes are in the page.
Code works great minus one thing…
How did you get your links to hyperlink?
@Damien: It sounds like this code is still a little above your skill level, because it definitely works when applied properly. You should hit up a programmers forum for more assistance.
@Dan: http://frankkoehl.com/2008/12/parse-urls-in-text-create-links
(Edit: inserted link because it actually wasn’t listed above)
The timezone thing works great, my issue is with the http:// that i put in my tweets, like twitpic etc… they aren’t made into hyperlinks on my website. Any thoughts?
Any thoughts on why the links in the twitter feed aren’t working?
First, this is a great tutorial and great product. I am also interested in getting the HTTP links to work as well. I see it working on your main page and I would like to know or see the code on how you got that to work.
My bad everyone, thought I had already linked to the article describing how to automatically create links out of URL’s in text, but apparently did not, so there you go.
I actually cover my entire setup in a 3-part series. I’ve added a small menu to the bottom of each article to make finding them a little easier. Add your comments and questions wherever necessary.
Thanks for the very useful code. I wanted a simplified version where I can use my own css.
as for the person getting the “Fatal error: Call to undefined function twitter_status() in” error…. your php does not have cURL support on your server. You will need to get the lib installed if you want this to work.
First article i have come across that was at the right level of simplicty/effectiveness of just getting your statuses online and working.
loving the no BS approach.
Thank you
@Kamran: You’re welcome. Don’t you hate when people package code examples to the point where customizing is a major PITA?
First article i have come across that was at the right level of simplicty/effectiveness of just getting your statuses online and working.
Which still blows my mind. I wrote this article back in November because I couldn’t find any code from, well, actual programmers. Almost a year later and the library of solid scripts out there is still really limited. Is that some kind of a sign?
loving the no BS approach.
I have a strict “no-BS” policy.
Nice script,
works perfect on my local server but not on the providers one. Are there more settings possible?
I get this message “Sorry, Twitter seems to be unavailable at the moment…” often.
grts Remco
I’m really liking this feed, but is there any way to display the user’s avatar and the timestamps?