API of the Week: Post to Twitter with PHP

I think I am going to start blogging examples of how to use API of some of the most popular social platforms out there…like facebook, Google OpenSocial, MySpace?, etc. And this will be weekly… hopefully, I won’t skip those…

But today, I am going to start with Twitter:

Like others I’ve found myself addicted to Twitter, the impossible to explain social networking site. If you’re reading this, have a twitter account and not already my friend then go ahead and add me… you might like me tweets.

Twitter deals nicely with SMS messaging, IM, subscription, and so on…Also, it has very simple XML and JSON based API.

To start with, you can play with CURL… something really simple, here is example:

curl -u username:password -d
status="twittering from curl" http://twitter.com/statuses/update.xml

And from there, you can do tons of stuff with CURL…

// Set username and password
$username = 'username';
$password = 'password';
// The message you want to send
$message = 'is twittering from php using curl';
// The twitter API address
$url = 'http://twitter.com/statuses/update.xml';
// Alternative JSON version
// $url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
// check for success or failure
if (empty($buffer)) {
echo 'message';
} else {
echo 'success';
}
?>

Obviously you could do more with the return than print out a success or failure message. The $buffer variable has the returned XML or JSON for you’re parsing pleasure.

I’m going to try out some of the other API methods too, probably play more with XSL or look more closely at the PEAR JSON module in building up a simple library as a quick search didn’t throw up much of interest and the API is nice and simple; making it fun to hack on.

Sphere: Related Content

Print This Post Print This Post

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)