PHP调用新浪API生成短链接
本示例展示了如何使用PHP调用新浪API来生成t.cn格式的短网址。内容供读者参考与借鉴。
新浪微博开放平台提供了将长链接转换为短链接的服务,能够将普通URL转化为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:待转换的长链接,必须进行URL编码,单次请求最多支持20个链接。 若需转换多个链接,需按如下格式拼接参数:url_long=aaa&url_long=bbb
获取source参数的步骤如下:
1. 访问 http://open.weibo.com/ ,在菜单中选择“微连接”->“网站接入”。 2. 点击“立即接入”,新建应用并填写应用名称,随后点击创建。 3. 应用创建成功后,页面显示的AppKey即为source参数的值,可用于后续短链接生成请求。
以下是测试代码示例:
<?php
$api = 'http://api.t.sina.com.cn/short_url/shorten.json'; // json
// $api = 'http://api.t.sina.com.cn/short_url/shorten.xml'; // xml
$source = '您申请的AppKey';
$url_long = 'https://www.jb51.net/';
$request_url = sprintf($api.'?source=%s&url_long=%s', $source, $url_long);
$data = file_get_contents($request_url);
echo $data;
?>
当请求返回JSON格式时,结果如下:
[
{
"url_short": "http:\/\/t.cn\/Rki0twp",
"url_long": "http:\/\/www.cnblogs.com\/daxiangxm",
"type": 0
}
]
当请求返回XML格式时,结果如下:
<?xml version="1.0" encoding="UTF-8"?>
http://t.cn/RBclsRo
https://www.jb51.net/
0
生成的短链接为 http://t.cn/RBclsRo ,访问该短链将跳转至 https://www.jb51.net/ 。
完整的调用方法代码如下:
<?php/**
* 调用新浪接口将长链接转为短链接
* @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
$source = '您申请的AppKey';
// 单个链接转换
$url_long = 'https://www.jb51.net/';
$data = getSinaShortUrl($source, $url_long);
print_r($data);
// 多个链接转换
$url_long = array('https://www.jb51.net/','https://www.jb51.net/','https://www.jb51.net/');
$data = getSinaShortUrl($source, $url_long);
print_r($data);
?>
程序输出结果如下:
Array( [0] => Array ( [url_short] => http://t.cn/RBclsRo [url_long] => https://www.jb51.net/ [type] => 0 ) )Array( [0] => Array ( [url_short] => http://t.cn/RBclsRo [url_long] => https://www.jb51.net/ [type] => 0 ) [1] => Array ( [url_short] => http://t.cn/RBclsRo [url_long] => https://www.jb51.net/ [type] => 0 ) [2] => Array ( [url_short] => http://t.cn/RBclsRo [url_long] => https://www.jb51.net/ [type] => 0 ) )
经过实际测试,该生成接口的运行表现较为稳定。
PS:本站推荐一款短网址生成工具,同样基于第三方API接口实现。
短链(短网址)在线生成工具: 点击使用
希望上述内容对读者的PHP编程实践有所帮助。