碎言碎语
咱们如果是玩php非静态网站,进行网页链接请求获取需要的数据,是必不可少的,不然难道“单机”不成?
全部数据文件本地化?这好像是静态网站的模式,而且就算是静态网站也不完全是静态的,也有js加持。
这显然不太现实了吧~~
封装
利用php的curl函数进行封装,具体代码如下:
function http_request($url,$timeout=30,$header=array()){
if (!function_exists("curl_init")) {
throw new Exception("server not install curl");
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
if (!emptyempty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
$data = curl_exec($ch);
list($header, $data) = explode("\\r\\n\\r\\n", $data);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
$matches = array();
preg_match("/Location:(.*?)\\n/", $header, $matches);
$url = trim(array_pop($matches));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
$data = curl_exec($ch);
}
if ($data == false) {
curl_close($ch);
}
curl_close($ch);
return $data;
}
结语
这个封装好了是可以直接套用的,也对301/302重定向的网页进行了进一步的处理!
ps:由于博客显示愿意,请注意url之类的符号,需要转码还原。
打开https链接的网页也是可以的~