user55655
user55655

Reputation: 47

Shorten link before sending to Twitter

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?

Upvotes: 0

Views: 566

Answers (1)

Mike
Mike

Reputation: 6934

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->results->nodeKeyVal->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

Upvotes: 1

Related Questions