首页 > Web开发 > 详细

PHP curl_setopt函数用法介绍补充篇

时间:2016-01-22 14:20:45      阅读:156      评论:0      收藏:0      [点我收藏+]

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;
?>

 

PHP curl_setopt函数用法介绍补充篇

原文:http://www.cnblogs.com/wuheng1991/p/5150669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!