zoukankan      html  css  js  c++  java
  • php数据抓取的三种方式

    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)
  • 相关阅读:
    [转] 传统 Ajax 已死,Fetch 永生
    React组件属性部类(propTypes)校验
    [转]webpack进阶构建项目(一)
    package.json 字段全解析
    [转]Nodejs基础中间件Connect
    [转]passport.js学习笔记
    [转]Travis Ci的最接底气的中文使用教程
    建站笔记1:centos6.5下安装mysql
    [软件人生]关于认知,能力的思考——中国城市里的无知现象片段
    一步一步学Spring.NET——1、Spring.NET环境准备
  • 原文地址:https://www.cnblogs.com/yaradish/p/9507987.html
Copyright © 2011-2022 走看看