在实际过程中我们会有这样的场景,就是发送短信的时候,里面需要嵌入我们的网址,可是网址都是很长的。

但是短信内容,最多只能七十个字左右,多余就会出现发送两条的情况,然而这并不是我们想要的。

所以,基于这种需求我们急需将长链接转为短链接。常用的可以看到新浪微博的分享地址。下面来看,如何实现?

新浪提供了长链接转为短链接的API,可以把长链接转为 t.cn/xxx 这种格式的短链接。

API: 

http://api.t.sina.com.cn/short_url/shorten.json (返回结果是JSON格式) 
http://api.t.sina.com.cn/short_url/shorten.xml (返回结果是XML格式)

请求参数: 

source 申请应用时分配的AppKey,调用接口时代表应用的唯一身份。 

url_long 需要转换的长链接,需要URLencoded,最多不超过20个。

多个url参数需要使用如下方式请求:url_long=aaa&url_long=bbb 

创建source方法 

1.进入http://open.weibo.com/ ,选择菜单 微连接->网站接入。 

2.点击立即接入,创建新应用,随便填写应用名称,点击创建。 

3.创建成功后,AppKey就是source参数的值,可以用于请求创建短链接。 

/**
 * 调用新浪接口将长链接转为短链接
 * @param  string        $source    申请应用的AppKey
 * @param  array|string  $url_long  长链接,支持多个转换(需要先执行urlencode)
 * @return array
 */
function getSinaShortUrl($source, $url_long){
    // 参数检查
    if(empty($source) || !$url_long){
        return false;
    }
    // 参数处理,字符串转为数组
    if(!is_array($url_long)){
        $url_long = array($url_long);
    }
    // 拼接url_long参数请求格式
    $url_param = array_map(function($value){
        return '&url_long='.urlencode($value);
    }, $url_long);
    $url_param = implode('', $url_param);
    // 新浪生成短链接接口
    $api = 'http://api.t.sina.com.cn/short_url/shorten.json';
    // 请求url
    $request_url = sprintf($api.'?source=%s%s', $source, $url_param);
    $result = array();
    // 执行请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $request_url);
    $data = curl_exec($ch);
    if($error=curl_errno($ch)){
        return false;
    }
    curl_close($ch);
    $result = json_decode($data, true);
    return $result;
}

// AppKey 以下是公用API,暂时可用。如失效,注册新浪开发者帐号即可
$source = 1681459862;

// 单个链接转换
$url_long = 'http://www.shuchengxian.com/';
$data = getSinaShortUrl($source, $url_long);
print_r($data);

// 多个链接转换
$url_long = array(
'http://www.shuchengxian.com/article/670.html',
'http://www.shuchengxian.com/article/654.html',
'http://www.shuchengxian.com/index.html'
);
$data = getSinaShortUrl($source, $url_long);
print_r($data);


Array
(
    [0] => Array
        (
            [url_short] => http://t.cn/R0Yf2ww
            [url_long] => http://www.shuchengxian.com/
            [type] => 0
        )
)
Array
(
    [0] => Array
        (
            [url_short] => http://t.cn/R0Yf2Ax
            [url_long] => http://www.shuchengxian.com/article/670.html
            [type] => 0
        )
    [1] => Array
        (
            [url_short] => http://t.cn/R0Yf2AJ
            [url_long] => http://www.shuchengxian.com/article/654.html
            [type] => 0
        )
    [2] => Array
        (
            [url_short] => http://t.cn/R0Yf2AM
            [url_long] => http://www.shuchengxian.com/index.html
            [type] => 0
        )
)

通过上面的方法,可以很轻松的实现用php生成短链接网址的功能。

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!