URL shortening using Google API

afbeelding van Developmentteam

Our friends from learn-drupal.in had this interesting piece of information, which is perhaps useful for others as well.
view the original page at: http://www.learn-drupal.in/api/goo-gl-api-php.html

  1. $longUrl = 'http://www.your-log-url-here.......';
  2. $apiKey = 'Your Google Api Key here';
  3. //You can get API key here : http://code.google.com/apis/console/
  4.  
  5. $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
  6. $jsonData = json_encode($postData);
  7.  
  8. $curlObj = curl_init();
  9.  
  10. curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
  11.  
  12. curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
  13.  
  14. curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
  15.  
  16. curl_setopt($curlObj, CURLOPT_HEADER, 0);
  17.  
  18. curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
  19.  
  20. curl_setopt($curlObj, CURLOPT_POST, 1);
  21.  
  22. curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
  23.  
  24. $response = curl_exec($curlObj);
  25.  
  26. $json = json_decode($response);
  27.  
  28. curl_close($curlObj);
  29. echo 'Shortened URL ->'.$json->id;

shadow