miriamdepaula

WordPress: Encurtador de URL usando Bit.ly API e cURL

Sep 10th, 2011
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.10 KB | None | 0 0
  1. /*
  2. Encurtador de URL usando a API do Bit.ly e PHP cURL
  3. Como usar: <?php bitly(); ?> ~> coloque no local onde quer que apareรงa a URL encurtada.
  4. */
  5.  
  6. function bitly()
  7. {
  8.     global $post;
  9.  
  10.     //login information
  11.     $url = get_permalink($post->ID);  //generates wordpress' permalink
  12.     $login = 'YOUR_LOGIN';  //your bit.ly login
  13.     $apikey = 'YOUR_BITLI_API_KEY'; //bit.ly apikey - quintaldosamba
  14.     $format = 'json';   //choose between json or xml
  15.     $version = '2.0.1';
  16.  
  17.     //create the URL
  18.     $bitly = 'http://api.bit.ly/shorten';
  19.     $param = 'version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
  20.    
  21.     //get the url
  22.     $ch = curl_init();
  23.     curl_setopt($ch, CURLOPT_URL, $bitly . "?" . $param);
  24.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  25.     $response = curl_exec($ch);
  26.     curl_close($ch);
  27.  
  28.     //parse depending on desired format
  29.     if(strtolower($format) == 'json')
  30.     {
  31.         $json = @json_decode($response,true);
  32.         echo $json['results'][$url]['shortUrl'];
  33.     }
  34.     else //xml
  35.     {
  36.         $xml = simplexml_load_string($response);
  37.         echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
  38.     }
  39. }
Add Comment
Please, Sign In to add comment