php

[php]google url Shortener 縮網址

最近因為剛好需要用到縮網址的功能,不然訊息會太長,所以找了這個 api來用。這邊紀錄一下給大家參考

記得 $longUrl要換成你要縮的網址

然後你得要去跟google申請一個伺服器端的api key(免費的) 把key打進去才行

google api key

<?php 
$longUrl = 'https://blog.davidou.org'; 
// Get API key from : http://code.google.com/apis/console/
$apiKey = '你要申請的api key打這邊';
$postData = array('longUrl' =&gt; $longUrl, 'key' =&gt; $apiKey);
$jsonData = json_encode($postData);

$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);

// Change the response json string to object
$json = json_decode($response);

curl_close($curlObj);
$shortLink = get_object_vars($json);
echo $shortLink['id'];

?>
Be the First to comment.

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

(若看不到驗證碼,請重新整理網頁。)