找回密码
 新建账号

dwz.cn t.cn短网址接口

[复制链接]
php 发表于 2015/9/23 04:51 | 显示全部楼层 |阅读模式
短网址,就是把一个很长的网址转化为简短的网址。常见的有百度的dwz.cn、新浪的t.cn、腾讯的url.cn等。
新浪的短网址t.cn最简单,直接以GET方式打开http://api.t.sina.com.cn/short_url/shorten.json?source=3577626330&url_long=http://www.51-n.com即可,其中红色部分为转换前的长网址,如果需要以xml形式返回,把shorten.json换成shorten.xml即可。将得到的如下数据稍事处理即可得到长网址对应的短链接:http://t.cn/8kuSvrO
[{"url_short":"http://t.cn/8kuSvrO","url_long":"http://www.51-n.com/","type":0}]

更多细节参见新浪短网址接口新浪短网址还原接口

百度的短网址API接口
以POST方式向http://dwz.cn/create.php发送content为url=http://www.51-n.com/即可。
对于PHP来说,可以使用cURL或者file_get_contents+context,实例代码如下。
由于是实例代码,短网址转换函数将直接返回转换成功以后的短网址,形如:http://dwz.cn/1L952P
更多细节参见:http://dwz.cn/api
  1. <?php
  2.         /* 百度短网址接口
  3.          * @Author 吴先成
  4.          * @param string $url 需要转换为短网址的原始网址
  5.          * @return string | bolean 成功时返回短网址,失败时返回false
  6.         */
  7.         function urlShorten($url=''){
  8.                 $cxt=stream_context_create(
  9.                         array(
  10.                                 'http'=>array(
  11.                                         'method'=>'POST',
  12.                                         'header'=>array(
  13.                                                 'Content-Type: application/x-www-form-urlencoded'
  14.                                         ),
  15.                                         'content'=>'url='.$url,
  16.                                         'timeout'=>1
  17.                                 )
  18.                         )
  19.                 );
  20.                 $rsp=@file_get_contents('http://dwz.cn/create.php',0,$cxt);
  21.                 if($rsp){
  22.                         if($json=json_decode($rsp)){
  23.                                 if($json->status===0){
  24.                                         return $json->tinyurl;
  25.                                 }
  26.                         }
  27.                 }
  28.                 return false;
  29.         }

  30.         echo urlShorten('http://www.51-n.com/');
复制代码

手机版|轻松E站

GMT+8, 2024/4/26 03:26

快速回复 返回顶部 返回列表