1、fopen、fgets方式抓取数据
$file = fopen(“yaradish.cn”,"r"); #打开资源,并绑定到一个stream上 while(!feof($file)){ #知道到达底部 $content.=fgets($files); #写入 } echo $content;
2、file_get_contents 方式
2.1、get方式抓取(最简单的方式只需要一个函数)
$content = file_get_contents('yaradish.cn'); echo $content;
2.2、post方式抓取
注:使用此方式的时候,可能会报错:‘无法找到包装器https,你在配置php时忘了配置它吗‘?(谷歌翻译)
出现这个问题不要紧张,只修改修改配置文件php.ini即可。方法如下
php_openssl.dll #打开注释,重启apache
代码:
$data = array('name' =>'yaradish'); #参数 $data = http_build_query($data); #将参数数组转换为请求字符串 $option = array( 'http' =>array( #声明协议 'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', #自己打的时候多看几遍,要不然直接复制 'content' => $data ) )
$url = 'http://www.yaradish.cn';
$content = stream_context_create($option); #模拟post,创建流stream
$result = file_get_content($url,false,$content);
echo $result;
3、curl方式抓取
使用这个方法抓取存在https协议的页面时会遇到一个问题,页面显示为空;原因是忽略了http和https的区别,解决办法有二:①将https换为http;②利用参数禁用ssl证书验证,即禁用https的加密认证
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,flase); 禁用curl验证对等证书 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,flase); 检测服务器域名和证书上的是否一致
代码:
$ch = curl_init(); #初始化 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $content = curl_exec($url); curl_close($ch)