使用Bitly API缩短url


Using Bitly API to shorten URLs

我在这个网站上找到了Bitly的API代码。我很难让它为一个名为$fullurl的变量创建并返回一个稍微缩短的URL。我该怎么做呢?

EDIT:没有出现错误代码,只是没有显示稍微缩短的URL。

EDIT 2: var_dump($response);返回NULL

EDIT 3:我确实用我的API登录和密钥替换了我的。

EDIT 4:我在原始教程的一个评论中找到了答案。我的问题对所有PHP专业人员来说都太基本了:我只需要在末尾添加echo bitly_shorten($fullurl);

提前感谢,

约翰

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;
    }
}

改为:

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;
  }
}

似乎有点。Ly已经更新了他们的API,请访问

http://code.google.com/p/bitly-api/wiki/ApiDocumentation Authentication_and_Shared_Parameters

的api。

url似乎是这样的, http://api.bitly.com/v3/shorten?.....

他们说的新版本是3,而你的代码是2.0.1

当你使用一个在线服务的api时,最好从他们的网站上获取,而不是从任何第三方网站或博客上获取。

我在原始教程的一个评论中找到了答案。我的问题对所有PHP专业人员来说都太基本了:我只需要在末尾添加echo bitly_shorten($fullurl);