PHP 获取网络接口文件流

获取网络接口里面的文件流

php开发调用各种接口在所难免,有时须要传递非常多參数。

在传递參数过程中 '&' 有时会被 解析成 ‘&’导致请求失败

经过查找资料和比較,发现php提供了多种方法:cUrl、fopen、file_get_contents等,就操作性、可靠性和高效来说 cURL还是不错的。

參考案比例如以下:

    /**
     * 获取网络接口里面的文件流
     **/
    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调用:

 $url = "http://zhibo.fx678.com/index.php?

page=htnews&ps=$size&time=$time"; GetWebFileStream($url);

POST调用:

$strURL = "http://reschart.fx678.com/fx678dataWebService/UpdateDataContext.asmx/GetWillAndPublishedDateS";
$urlParams ="willtop=$willSize&top=$size&Clientdate=$clientDate&Key=$md5_key";

$strJSON = GetWebFileStream($strURL,$urlParams,'post');
以上案例仅供參考,很多其它cUrl 知识点请參考php手冊!



原文地址:https://www.cnblogs.com/blfbuaa/p/6786037.html