Twitter Status v1.0 (with JSON and cURL in PHP)
December 2nd, 2009So I was looking for a dead simple way to output my status from twitter to a webpage. Almost everyone does it these days and I thought it would be a piece of cake to find a ready-made solution. I searched, found a bunch of insightful (or not) scripts but none actually made the cut. They would be either too massive, supporting functions I didn’t need, or process things in a peculiar way which made me uncomfortable.
The better candidate did a simple cURL request but used SSL and returned the content from an XML. Why, why, why? Why use SSL when twitter is supposed to be public, and why use XML when you have the option to use a perfectly slimmed-down JSON instead?
It’s agreed that cURL can do the job nicely without the need of special programming. And you can have an additional layer of caching on the server-side along with the caching in JavaScript through the AJAX call to this script.
In it’s core – the script is only driven by a single request:
curl_setopt($ch, CURLOPT_URL, 'http://twitter.com/statuses/user_timeline.json' . $params ); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This is guided by the following parameters – quite self-explanatory:
$config = array( 'screen_name' => 'YOURTWITTERNAME', 'count' => '1', );
To flesh-out the text we want to present we do the following:
$data = json_decode( $response ); $text = $data[0]->{"text"};
Usage:
To contain this process so it doesn’t affect the loading time of the webpage it is better to inject it with an AJAX request. It is rather fluid how you’d want to do this (name the markup container whatever and style it in CSS however) but I chose the dead simple way (again):
<div id="twitter-status"> <script type="text/javascript"> $(document).ready(function() { $.get("twitter_status.php", function(data){$("#twitter-status").html(data);} ); }); </script> </div>
This was used here, where you can see it in action: http://makis.tracend.com.au
Wish list:
The one major glitch with this simplistic approach is that it assumes that the latest tweet will always be a tweet – replies and mentions will probably not work and there is no “skip to next” function. Multiple tweets are also not supported. I also miss automatic linking but again I didn’t want to bloat the script with extra functions – for now… maybe an upscale version will come soon…
Version: 1.0
Language: PHP
File size: 1,39kb

