短連接,通俗來講,就是將長的URL網址,經過程序計算等方式,轉換爲簡短的網址字符串。
國內各大微博都推出了本身的短連接服務。例如新浪微博、騰訊微博等。php
拿到本身的AppKey後,替換類的成員屬性$appKey的值便可,以下這樣的,$shortUrl是API請求地址html
// APPkey,我在網上找的(https://fengmk2.com/blog/appkey.html),能夠本身申請 protected $appKey = '569452181'; // 轉短鏈接API地址 protected $shortUrl = 'https://api.weibo.com/2/short_url/shorten.json?';
其餘的,基本不須要配置,直接實例化類ShortLink,而後調用方法getShortUrl便可,須要說明的是長連接URL數組$longUrl裏的值能夠傳多個值json
固然了,爲了方便,我寫爲一個類,能夠根據本身的須要,進行調整,知足本身的需求便可。segmentfault
<?php /** * 經過新浪微博API,生成短連接,支持一次性轉多個長連接 * Class shortClass * @time 2018-08-14 * @author gxcuizy */ Class ShortLink { // APPkey,我在網上找的(https://fengmk2.com/blog/appkey.html),能夠本身申請 protected $appKey = '569452181'; // 轉短鏈接API地址 protected $shortUrl = 'https://api.weibo.com/2/short_url/shorten.json?'; /** * 生成短連接 * @param array $longUrl 長連接數組 * @return array 返回短鏈接數據 */ public function getShortUrl($longUrl = []) { $code = true; $msg = '請求成功!'; $result = []; // 長連接數組爲空,不處理 if (empty($longUrl)) { $code = false; $msg = '長連接數據不能爲空'; return ['code' => $code, 'msg' => $msg, 'result' => $result]; } // 拼接請求URL $longUrlStr = $this->_getLongUrl($longUrl); $shortUrl = $this->shortUrl; $appKey = $this->appKey; $param = 'source=' . $appKey . '&' . $longUrlStr; $curlUrl = $shortUrl . $param; // 發送CURL請求 $result = $this->_sendCurl($curlUrl); return ['code' => $code, 'msg' => $msg, 'result' => $result]; } /** * 獲取請求URL字符串 * @param array $longUrl 長連接數組 * @return string 長連接URL字符串 */ private function _getLongUrl($longUrl = []) { $str = ''; foreach ($longUrl as $url) { $str .= ('url_long=' . $url . '&'); } $newStr = substr($str, 0, strlen($str) - 1); return $newStr; } /** * 發送CURL請求(GET) * @param string $curlUrl 請求地址 * @return array 返回信息 */ private function _sendCurl($curlUrl) { // 初始化 $ch = curl_init(); // 設置選項,包括URL curl_setopt($ch, CURLOPT_URL, $curlUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // 執行並獲取HTML文檔內容 $output = curl_exec($ch); // 釋放curl句柄 curl_close($ch); // Json數據轉爲數組 $result = json_decode($output, true); return $result; } } // 實例化對象 $shortObj = new ShortLink(); // 多個鏈接能夠直接放到數組中,相似$longUrl = ['url1', 'url2', ……] $longUrl = ['http://blog.y0701.com/index.html']; // 開始轉長連接爲短連接 $result = $shortObj->getShortUrl($longUrl); print_r($result);
上面說到的網上查找獲得的一些AppKey,由於來源不明,因此,不建議用於生產環境,須要用於生產環境的話,建議直接在新浪微博開發者平臺裏建立本身的應用就行。api
原文地址:https://segmentfault.com/a/1190000016004175數組