zoukankan      html  css  js  c++  java
  • PHP curl_setopt函数用法介绍补充篇

    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;
    ?>
  • 相关阅读:
    从a文件判断是否删除b文件中的行(sed示例)
    绝对路径的表示方式为什么是"/usr"而不是"//usr"
    判断ssh远程命令是否执行结束
    彻底搞懂shell的高级I/O重定向
    Resource Agent:LSB和OCF
    流程控制语句(MySQL/MariaDB )
    MySQL/MariaDB中游标的使用
    翻译:DECLARE HANDLER语句(已提交到MariaDB官方手册)
    从集合的无序性看待关系型数据库中的"序"
    MariaDB/MySQL存储过程和函数
  • 原文地址:https://www.cnblogs.com/wuheng1991/p/5150669.html
Copyright © 2011-2022 走看看