在使用前,请先到这里申请API Key:http://code.google.com/apis/console/
短网址的生成需要使用POST提交数据,所以使用了curl,短网址的还原可以直接使用file_get_contents()函数。不过为了统一,我也使用了curl来处理,现在感觉curl真的是非常有用,等有空对curl还要加大学习哈。
<?php
function shortenGoogleUrl($long_url){
$apiKey = ‘API-KEY’; //Get API key from : http://code.google.com/apis/console/
$postData = array(‘longUrl’ => $long_url, ‘key’ => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, ‘https://www.googleapis.com/urlshortener/v1/url’);
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);
curl_close($curlObj);
$json = json_decode($response);
return $json->id;
}
?>
<?php
function expandGoogleUrl($short_url){
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, ‘https://www.googleapis.com/urlshortener/v1/url?shortUrl=’.$short_url);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curlObj);
curl_close($curlObj);
$json = json_decode($response);
return $json->longUrl;
}
?>
原文地址:http://www.biaodianfu.com/php-google-urlshortener-api.html