最近因為剛好需要用到縮網址的功能,不然訊息會太長,所以找了這個 api來用。這邊紀錄一下給大家參考
記得 $longUrl要換成你要縮的網址
然後你得要去跟google申請一個伺服器端的api key(免費的) 把key打進去才行
<?php $longUrl = 'https://blog.davidou.org'; // Get API key from : http://code.google.com/apis/console/ $apiKey = '你要申請的api key打這邊'; $postData = array('longUrl' => $longUrl, 'key' => $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']; ?>