Using Bitly API to shorten URLs
I found the Bitly API code below on this site. I'm having a hard time getting it to create and then echo a Bitly shortened URL for a variable called $fullurl. How would I do that?
EDIT: No error code appears, just no bitly shortened URL is shown.
EDIT 2: var_dump($response);
returns NULL
EDIT 3: I did replace the API login and key with my mine.
EDIT 4: I found the answer in one of the comments on the original tutorial. My question was too basic for all you PHP pros: I simply needed to add echo bitly_shorten($fullurl);
at the end.
Thanks in advance,
John
function bitly_shorten($url)
{
$query = array(
"version" => "2.0.1",
"longUrl" => $url,
"login" => API_LOGIN, // replace with your login
"apiKey" => API_KEY // replace with your api key
);
$query = http_开发者_运维百科build_query($query);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.bit.ly/shorten?".$query);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
if($response->errorCode == 0 && $response->statusCode == "OK") {
return $response->results->{$url}->shortUrl;
} else {
return null;
}
}
Change it to:
function bitly_shorten($url){
$query = array(
"version" => "2.0.1",
"longUrl" => $url,
"login" => API_LOGIN, // replace with your login
"apiKey" => API_KEY // replace with your api key
);
$query = http_build_query($query);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.bitly.com/v3/shorten?".$query);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
if( $response->status_txt == "OK") {
return $response->data->url;
} else {
return null;
}
}
It seems that bit.ly had updated their api , please visit
http://code.google.com/p/bitly-api/wiki/ApiDocumentation#Authentication_and_Shared_Parameters
for api..
The url seems to be something like this, http://api.bitly.com/v3/shorten?.....
The new version they stated is 3 and in your code its 2.0.1
Whenever you are using an api of an online service its better to get it from their site instead of getting that from any third party site or blog..
I found the answer in one of the comments on the original tutorial. My question was too basic for all you PHP pros: I simply needed to add echo bitly_shorten($fullurl);
at the end.
精彩评论