php curl request interface and get data

WBOY
Release: 2016-08-08 09:20:28
Original
1476 people have browsed it

When we are doing PHP development, we often need to test the interface, or more conveniently call the interface of some existing modules, get the results and perform subsequent operations. We can simulate submitting post and get requests through curl. Come and implement these functions.

The following is the encapsulation of curl's post and 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">	</span>//获得数据并返回
        return $data;
    }
}
Copy after login

After that, you can call the interface and get the data through CURL::curl_post($url,$array) or CURL::curl_get($url);.

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the php curl request interface and obtains data, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template