goo.gl URL shorten using API & API key - v2


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function getgoogl($longUrl){
  2.  
  3. //This is the URL you want to shorten
  4. $apiKey = 'AIzaSyDMgK9gpIIokl7ClMqMXHZQ7wv_xzRwMHs';
  5. //Get API key from : http://code.google.com/apis/console/
  6.  
  7. $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
  8. $jsonData = json_encode($postData);
  9.  
  10. $curlObj = curl_init();
  11.  
  12. curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey);
  13. curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
  14. curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
  15. curl_setopt($curlObj, CURLOPT_HEADER, 0);
  16. curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
  17. curl_setopt($curlObj, CURLOPT_POST, 1);
  18. curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
  19.  
  20. $response = curl_exec($curlObj);
  21.  
  22. //change the response json string to object
  23. $json = json_decode($response);
  24.  
  25. curl_close($curlObj);
  26.  
  27. return $json->id;
  28.  
  29. }
  30.  
  31. // call function getgoogl("http://www.longurlhere.com");

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.