HOWTO: Creating the Simplest Twitter API Client in PHP
May 21st, 2009 by admin | Filed under Twitter.Do you run a website? Heard about the Twitter API? Try it!
I have been playing around with the Twitter API lately, all though the OpenAuth is a bit more hassle they still support the ‘old’ API for a bit longer. Twitter has not set a definitive date on when these applications will stop working but it will happen.
In the mean time, it’s a good way to learn how to play with the API without dealing with all the openauth stuff.
I have created an example function that you can use to create your own Twitter applications, it does not support or have any sense of sessions but if you intend to play, check it out! Extend it, tell me about your changes!
You need Zend for this example to work, and more specifically the Zend Json decoder part. It helps parsing the JSON information sent from Twitter.
<?php
/* Simple Twitter API Client Example utilizing Zend/Json
* http://www.cfg.no/ – Espen Holm Nilsen 20090521
*/
require_once ‘Zend/Json.php’;function twitterJsonGet ($strUser, $strPassword, $strUrl) {
$strBasicAuth = base64_encode($strUser . ‘:’ . $strPassword);
$strRequest = “GET ” . $strUrl . “.json HTTP/1.1\nAuthorization: Basic ” . $strBasicAuth . “\nUser-Agent: PHPTwitter 1.0 (http://www.cfg.no)\nHost: twitter.com\nAccept: */*\r\n\r\n”;
$fd = fsockopen(‘twitter.com’, 80);
if (!$fd)
die(“Could not connect to Twitter”);
fputs($fd, $strRequest);
while (!feof($fd)) $buf .= fgets($fd, 1024);$res = explode(“\r\n\r\n”, $buf);
if (!preg_match(“/^HTTP\/1\.1\s200\sOK/”, $res[0]))
return FALSE;return Zend_Json::Decode($res[1]);
}if ($_POST['twitteruser'] && $_POST['twitterpass']) {
$user = twitterJsonGet($_POST['twitteruser'], $_POST['twitterpass'], ‘/account/verify_credentials’);
print “You are <a href=’http://twitter.com/” . $user['screen_name'] . “‘>” . $user['screen_name'] . “</a><br>”;
print “You follow ” . $user['friends_count'] . ‘ people and have ‘ . $user['followers_count'] . ” followers.<br>”;
}?>
<form action=’?’ method=’POST’>
Twitter username<br><input type=”text” name=”twitteruser”><br>
<br>
Twitter password<br><input type=”password” name=”twitterpass”><br>
<input type=”submit” value=”Who am I?”>
</form>
The application example runs live here: http://arpa.no/twitter.php
Since it’s Twitter specific, you should Tweet it, or retweet if you saw it in a Tweet!
Good luck, let me know how you do!
Tags: php, Twitter, twitter api

Follow me on Twitter