Inspired by the simple tweet to twitter function by Fabian Potencier I have built a stupidly simple url shorter for bit.ly. Something you are probably going to want to do if you are sending tweets via PHP.
function shorten($url, $login, $apikey)
{
$api_url = "http://api.bit.ly/shorten?version=2.0.1&
longUrl=".urlencode($url)."&login=".$login."&
apiKey=".$apikey;
$ret = file_get_contents($api_url);
$data = json_decode($ret);
if($data instanceof stdClass && property_exists($data, "errorCode") && $data->errorCode==0)
{
foreach($data->results as $result)
{
if(isset($result->shortUrl))
{
return $result->shortUrl;
}
}
}
return $url;
}
In the application where I am using this function I have defined the login name and api key as constants, so you can do away with 2 function calls.
Also handily it returns the original url if bit.ly fails.