Heim  >  Artikel  >  Backend-Entwicklung  >  php curl请求接口并获取数据

php curl请求接口并获取数据

WBOY
WBOYOriginal
2016-08-08 09:20:281443Durchsuche

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

下面是对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;
     }
    /*
     * url:访问路径
     * array:要传递的数组
     * */
    public static function curl_post($url,$array){

        $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);
        //设置post数据
        $post_data = $array;
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
<span style="white-space:pre">	//获得数据并返回
        return $data;
    }
}

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了php curl请求接口并获取数据,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:ThinkPHP上传文件总结Nächster Artikel:php扩展xdebug基本使用