views:

32

answers:

1

I have a PHP loop that displays different headlines and their links. I'd like to send those links to Twitter with an auto-generated short link via Bitly. This is how the link is structured:

<a href="http://twitter.com/home?status=This is the headling {dynamic Permalink}">Share on Twitter</a>

How can I create a shortened link after the loop has created the actual permalink?

A: 

You need to register at bit.ly and get the API key.

function make_bitly_url($url, $login, $apiKey, $format = 'xml',$version = '2.0.1', $history=1 ) {

    if(substr($url, 0, 7) != 'http://')
        $url = 'http://'.$url;

    $bitly = 'http://api.bit.ly/shorten';
    $param = 'version='.$version.'&longUrl='.urlencode($url).'&login='
    .$login.'&apiKey='.$apiKey.'&format='.$format.'&history='.$history;
    //get the url
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $bitly . '?' . $param);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    //parse depending on desired format
    if(strtolower($format) == 'json') {
    $json = @json_decode($response,true);
    return $json['results'][$url]['shortUrl'];
    } else {
    $xml = simplexml_load_string($response);
    return 'http://bit.ly/'.$xml-&gt;results-&gt;nodeKeyVal-&gt;hash;
    }
} // end: function

Now the $login variable is your login, the $apeKey your apiKey and $url is the long url, you want to be short and the function outputs the short bit.ly address.

More at: http://code.google.com/p/bitly-api/wiki/ApiDocumentation

Mike
Thanks for your help, Mike. Not quite sure how to integrate the code you provided into my actual page though. Would you be willing to help me with a full example?
The integration is pretty simple. You just add this function to your code, somewhere at the top and then when you want to use it, just use it like this: make_bitly_url($url, $login, $apiKey);
Mike