首页 > 解决方案 > Bitly API 成功缩短 URL 但长 URL 错误

问题描述

我尝试缩短 URL 并使用此代码来缩短 URL,它可以缩短但长 URL 是错误的

<?php


/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
    //create the URL
    $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

    //get the url
    //could also use cURL here
    $response = file_get_contents($bitly);

    //parse depending on desired format
    if(strtolower($format) == 'json')
    {
        $json = @json_decode($response,true);
        return $json['results'][$url]['shortUrl'];
    }
    else //xml
    {
        $xml = simplexml_load_string($response);
        return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
    }
}

?>

打电话,我用这个代码:

<?php /* usage */
$short = make_bitly_url('http://test.com./sub/<?php echo $idplus;?>','user','API Key','json');
echo 'Bitly :  '.$short; 
?>

$idplus 是我输入 url 时得到的唯一值。当我使用此代码时,网址可以缩短但长网址http://test.com/sub/<?php echo $idplus;?>不会http://test.com/sub/idplus,请帮我解决这个问题,因为我对编码一无所知:(

为了弄清楚这种情况,当我访问一个页面时,test.com/test/123我想用这个长 URL 创建一个短 URLabc.com/com/123

标签: phpapi

解决方案


对于调用使用这个:

<?php /* usage */
$url = 'http://test.com./sub/' . $idplus;
$short = make_bitly_url($url,'user','API Key','json');
echo 'Bitly :  '.$short; 
?>

推荐阅读