|
没什么好讲了,重要的地方我都在代码中注释了,主要是APP_KEY,这个需要你自己去新浪的开放平台申请,地址:http://open.t.sina.com.cn/ 。注册后随便添加个app就可以得到key了(在没有APP_KEY的情况下你也可以通过oAuth认证方式实现)。
下面是PHP的调用代码:
3 | define('SINA_APPKEY', '你的App_Key'); |
5 | function curlQuery($url) { |
8 | "Content-type: application/json" |
11 | //初始化curl,当然,你也可以用fsockopen代替 |
12 | $curl_obj = curl_init(); |
15 | curl_setopt($curl_obj, CURLOPT_URL, $url); |
18 | curl_setopt($curl_obj, CURLOPT_HTTPHEADER, $addHead); |
21 | curl_setopt($curl_obj, CURLOPT_HEADER, 0); |
24 | curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, 1); |
27 | curl_setopt($curl_obj, CURLOPT_TIMEOUT, 15); |
30 | $result = curl_exec($curl_obj); |
33 | curl_close($curl_obj); |
38 | //简单处理下url,sina对于没有协议(http://)开头的和不规范的地址会返回错误 |
39 | function filterUrl($url = '') { |
40 | $url = trim(strtolower($url)); |
41 | $url = trim(preg_replace('/^http:\/\//', '', $url)); |
45 | return urlencode('http://' . $url); |
49 | function sinaShortenUrl($long_url) { |
50 | //拼接请求地址,此地址你可以在官方的文档中查看到 |
51 | $url = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . SINA_APPKEY .'&url_long=' . $long_url; |
54 | $result = curlQuery($url); |
56 | //下面这行注释用于调试,你可以把注释去掉看看从sina返回的信息是什么东西 |
57 | //print_r($result);exit(); |
60 | $json = json_decode($result); |
63 | if (isset($json->error) || !isset($json[0]->url_short) || $json[0]->url_short =='') |
66 | return $json[0]->url_short; |
69 | //根据短网址获取长网址,此函数重用了不少sinaShortenUrl中的代码,以方便你阅读对比,你可以自行合并两个函数 |
70 | function sinaExpandUrl($short_url) { |
71 | //拼接请求地址,此地址你可以在官方的文档中查看到 |
72 | $url = 'http://api.t.sina.com.cn/short_url/expand.json?source=' . SINA_APPKEY .'&url_short=' . $short_url; |
75 | $result = curlQuery($url); |
77 | //下面这行注释用于调试,你可以把注释去掉看看从sina返回的信息是什么东西 |
78 | //print_r($result);exit(); |
81 | $json = json_decode($result); |
84 | if (isset($json->error) || !isset($json[0]->url_long) || $json[0]->url_long =='') |
87 | return $json[0]->url_long; |
91 | $url = 'http://www.xingdonghai.cn'; |
93 | $url = filterUrl($url); |
94 | $short = sinaShortenUrl($url); |
95 | $ulong = sinaExpandUrl($short); |
96 | echo "源网址:{$ulong}<br />短网址:{$short}"; |
最后附官方API文档地址:
关于短网址的一些API:http://t.cn/hd5b1z
shorten:http://t.cn/hd5GxC
expand:http://t.cn/hd5Gl3
http://www.xingdonghai.cn/php-sina-short-url-api-json/ |
|
|