PHP curl_setopt函数用法介绍补充篇
2024-08-22 13:17:28
1.curl数据采集系列之单页面采集函数get_html
单页面采集在数据采集过程中是最常用的一个功能 有时在服务器访问限制的情况下 只能使用这种采集方式 慢
但是可以简单的控制 所以写好一个常用的curl函数调用是很重要的。
<?php
$url = 'http://www.baidu.com';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_TIMEOUT,5);
$html = curl_exec($ch);
if($html !== false){
echo $html;
} ?>
或者:
<?php
function get_html($url,$options = array()){
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 5;
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$html = curl_exec($ch);
curl_close($ch);
if($html === false){
return false;
}
return $html;
} $url = 'http://www.baidu.com';
echo get_html($url); ?>
2.Referer的采集
对于一些程序,它可能判断来源网址,如果发现referer不是自己的网站,则拒绝访问,
这时候,我们就需要添加CURLOPT_REFERER参数,模拟来路,使得程序能够正常采集。
<?php
$keyword = 'PHP cURL';
//参数方法一
// $post = 'wd=' . urlencode($keyword); //参数方法二
$post= array(
'wd'=> urlencode($keyword),
);
$url = 'http://localhost/ajax_page/';
$refer = 'http://localhost/ajax_page/'; //来路地址 $ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据不直接输出
curl_setopt($ch, CURLOPT_REFERER, $refer); //来路模拟
curl_setopt($ch, CURLOPT_POST, 1); //发送POST类型数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //POST数据,$post可以是数组,也可以是拼接
$content = curl_exec($ch); //执行并存储结果
curl_close($ch); echo $content;
?>
最新文章
- volatile
- 显示图片的(自定义)吐司Toast
- AX7: Quick and easy debugging
- Qt5 发布的exe应用程序Windows下无法执行的问题解决方案
- 软考之PV操作(同步)
- web.config中httpRunTime的属性
- Java运算符优先级(转)
- 算法训练 Hankson的趣味题
- The APR based Apache Tomcat Native library 异常解决办法
- RT/Metro商店应用如何如何获取图片的宽高
- Spring中的BeanUtils与apache commons中的BeanUtils用法[1]
- 【go】脑补框架 Express beego tornado Flux reFlux React jsx jpg-ios出品
- JVM内存回收机制
- 性能更好的js动画实现方式——requestAnimationFrame
- 分页加查询的sql语句
- IDEA 15 社区版 Maven项目 启动Tomcat调试
- 关于callContext
- JSON的BUG
- 机器学习-kNN
- mongodb 数据自动备份