PHP获取接口数据(模拟Get)

来源:互联网 发布:fifaonline316普卡数据 编辑:程序博客网 时间:2024/06/05 21:14

当我们在做PHP开发的时候,很多时候需要对接口进行测试,或者更方便的调用一些已有模块的接口,取到结果并进行后续操作,我们可以通过curl进行模拟提交post和get请求,来去实现这些功能。

之后就可以通过CURL::curl_post($url,$array)或者CURL::curl_get($url);的方式调用接口并得到数据了。

 

下面是对curl的post和get的封装

复制代码
<?php    /**   * Created by PhpStorm.   * User: thinkpad   * Date: 2015/7/17 0017   * Time: 13:24   */  class Action  {      public static function curl_get($url){               $testurl = $url;             $ch = curl_init();               curl_setopt($ch, CURLOPT_URL, $testurl);                //参数为1表示传输数据,为0表示直接输出显示。             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);              //参数为0表示不带头文件,为1表示带头文件             curl_setopt($ch, CURLOPT_HEADER,0);             $output = curl_exec($ch);              curl_close($ch);              return $output;       }    public static function curl_post($url){            $curl = curl_init();          //设置提交的url          curl_setopt($curl, CURLOPT_URL, $url);          //设置头文件的信息作为数据流输出          curl_setopt($curl, CURLOPT_HEADER, 0);          //设置获取的信息以文件流的形式返回,而不是直接输出。          curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);          //设置post方式提交          curl_setopt($curl, CURLOPT_POST, 1);        //执行命令          $data = curl_exec($curl);          //关闭URL请求          curl_close($curl);        //获得数据并返回          return $data;      }  }