PHP gets network interface file stream

Get the file stream in the network interface

It is inevitable for PHP development to call various interfaces, and sometimes many parameters need to be passed.

During the process of passing parameters, '&' is sometimes parsed into ‘&’ causing the request to fail.

After searching for information and comparing, I found that PHP provides a variety of methods: cUrl, fopen, file_get_contents, etc. In terms of operability, reliability and efficiency, cURL is still good.

 

Reference cases are as follows:

    /**
     * 获取网络接口里面的文件流
     **/
    public function GetWebFileStream($strUrl,$urlParams = '',$type = 'get'){
        $stream = "";
        if(!isset($strUrl) || empty($strUrl))
            return "";


        //初始化
        $ch = curl_init();
        if($type === 'post'){
            curl_setopt_array($ch,[
                CURLOPT_URL              => $strUrl,
                CURLOPT_RETURNTRANSFER  => 1,
                CURLOPT_POST             => 1,
                CURLOPT_HEADER           => 0,
                CURLOPT_POSTFIELDS      => $urlParams
            ]);
        }
        else{
            curl_setopt_array($ch,[
                CURLOPT_URL              => $strUrl,
                CURLOPT_RETURNTRANSFER  => 1,
                CURLOPT_HEADER           => 0
            ]);
        }


        //输出结果
        $stream = curl_exec($ch);


        //判断curl请求是否超时
        if(curl_errno($ch)){
            $stream = file_get_contents($strUrl);
        }


        //关闭
        curl_close($ch);

        return $stream;
    }

GET call:

 $url = "http://xxx.xxx.xxx/xxx.php?page=htnews&ps=$size&time=$time";
 GetWebFileStream($url);

POST call:

$strURL = "http://xxx.com/xxx/xxx.asmx/xxx";
$urlParams ="xxx=$xxx&top=$xxx&xxx=$xxx&xxx=$xxx";

$strJSON = GetWebFileStream($strURL,$urlParams,'post');

The above cases are for reference only. For more cUrl knowledge points, please refer to the php manual!

 

 

 

Guess you like

Origin blog.csdn.net/yimiyuangguang/article/details/40742905