You know the dilemma, you want to write a simple tweeting PHP script and have to mess around with the Twitter API.
With the following small script you can tweet with a simple function call. It IS that simple (And SSL secured!!!).
Here’s the function:
function tweet($user, $pass, $text) {
unset($GLOBALS['tweetError']);
if(strlen($text) > 140) { $GLOBALS['tweetError'] = 'TEXT TOO LONG: '.$text; return false; }
$tweet = curl_init();
curl_setopt($tweet, CURLOPT_URL, 'https://www.twitter.com/statuses/update.xml');
curl_setopt($tweet, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($tweet, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tweet, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($user.':'.$pass)));
curl_setopt($tweet, CURLOPT_POST, 1);
curl_setopt($tweet, CURLOPT_POSTFIELDS, 'status='.utf8_encode($text));
if(!$return = curl_exec($tweet)) $GLOBALS['tweetError'] = 'CURL ERROR: '.curl_error($tweet);
else if($returnData = simplexml_load_string($return)) {
if(!isSet($returnData->error)) $GLOBALS['tweetSuccess'] = 'Created at: '.$returnData->created_at.'<br />Text: '.utf8_decode($returnData->text);
else $GLOBALS['tweetError'] = 'TWITTER ERROR: '.$returnData->error;
} else $GLOBALS['tweetError'] = 'RETURN IS NOT XML: '.$return;
curl_close($tweet);
return (isSet($GLOBALS['tweetError']))?false:true;
}
To make a tweet just call the function:
tweet("username", "password", "My cool tweet!");
The function returns “true” if successful or “false” if not.
To echo out the error or success messages, just use this code:
if(tweet("username", "password", "My cool tweet!")) {
echo 'Tweet Successful!<br />'.$GLOBALS['tweetSuccess'];
} else {
echo 'Tweet Error!<br />'.$GLOBALS['tweetError'];
}
If there was an error, the error description is saved in $GLOBALS['tweetError'], and if the tweet was successful, the time and the text itself is saved in $GLOBALS['tweetSuccess'].
Have fun and happy (automatic?) tweeting.