看到友情链接的网站有一个自带的api接口,能获取所有友情链接的icon图标,我觉得挺有意思的。
别人有的,我也要有,所以我下手下了一个这个小玩意儿,当做一个api使用就行了。
后期我也会把它加入到我现在网站底部友情链接的前面,给所有的链接自动获取他们对应的ico图标。
下面说说我的思路:
先获取到用户输入的网址,然后加入判断,条件符合之后直接进入下一步。
然后在获取目标站对方的源代码,从源代码中获取ico标签,之后获取对应的url,
对url进一步提取,提取出来之后封装返回给调用者。
我知道肯定还有很多更加简单的方法,但是我的这个写法也是可以运行的,就是有点儿浪费服务器资源。
不想自己搭建的,可以使用我的API:
使用方法:
https://api.mxooo.cn/ico/?url=https://boke.slhq.cn/
橙色部分是你需要获取的网址,一定要带上https或者http,因为我代码中没有自动补全网址的前缀。
演示截图:
api代码:
<?php header('Content-Type: text/html; charset=utf-8'); // 判断输入值是否为空 if(!empty($_GET['url'])){ // 判断是不是一个网址形式 $pattern="/(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?/"; if(preg_match($pattern,$_GET['url'])){ // 内部处理逻辑 run(); } }else{ return_error(201); } // 条件符合开始处理信息 function run(){ $url = $_GET['url']; $contents= get_curl($url); preg_match('/<link rel=".*?icon".*?href="(.*?)".*?>/', $contents,$icon); // 判断文件是否存在 // $array = @get_headers($icon[1],1); // var_dump(is_null($icon)); if(!is_null($icon)){ // 下面两行代码是获取目标数据之后在拿回来展现,需要消耗本地性能 header("Content-type: image/jpeg"); $now = @file_get_contents($icon[1]); exit($now); // 下面代码不消耗服务器性能,只通过客户端加载 // $img = '<img src='.$icon[1].' width="32px" height="32px" >'; // echo $img; }else{ return_error(404); } } // 返回错误信息 function return_error($code_cc){ if($code_cc===201){ $return_error = ['coed'=>201,'msg'=>'请检查您输入的网址对不对呦~']; exit(json_encode($return_error,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)); }elseif($code_cc===404){ $return_error = ['coed'=>404,'msg'=>'现在系统获取不到目标站的信息~']; exit(json_encode($return_error,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)); } } //GET-curl封装 function get_curl($url, $post=0, $referer=0, $cookie=0, $header=0, $ua=0, $nobaody=0){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $httpheader[] = "Accept:application/json"; $httpheader[] = "Accept-Encoding:gzip,deflate,sdch"; $httpheader[] = "Accept-Language:zh-CN,zh;q=0.8"; $httpheader[] = "Connection:close"; curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader); if ($post) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); } if ($header) { curl_setopt($ch, CURLOPT_HEADER, true); } if ($cookie) { curl_setopt($ch, CURLOPT_COOKIE, $cookie); } if($referer){ if($referer==1){ curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f='); }else{ curl_setopt($ch, CURLOPT_REFERER, $referer); } } if ($ua) { curl_setopt($ch, CURLOPT_USERAGENT, $ua); } else { curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0"); } if ($nobaody) { curl_setopt($ch, CURLOPT_NOBODY, 1); } curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_ENCODING, "gzip"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $ret = curl_exec($ch); curl_close($ch); return $ret; }