Create Bit.ly short URLs using PHP

One of the more popular URL shortening services is Bit.ly. I’ve showed you how to create short URLs with TinyURL and Is.Gd, so why not show you how to create Bit.ly URLs remotely?

PHP Code

/* make a URL small */
function make_bitly_short_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

//get the url
//could also use cURL here
$response = file_get_contents($bitly);

//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
return $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}

/* usage */
$url= make_bitly_short_url(' http://www.phplatesttutorials.com/create-bit-ly-short-urls-using-php','saqlain786','R_20f4006565af394554264ebab56328b9','json');
echo 'Short URL is: '.$url;

Note that Bit.ly requires you to sign up for an account. Once you have an account, you may attain your login and URL information. I’ve also created functionality to recieve the shortened URL using JSON or XML.

Cheers, That’s all :)

About the author

PHP | MVC | Codeignitor | Zend | Yii | Smarty | Android | Laravel Expert Senior Software Developer.I love my job and feel happy to working on new ideas and technologies.

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Name (required)
Email (required)