Home > Backend Development > PHP Tutorial > PHP 获取网络接口文件流

PHP 获取网络接口文件流

WBOY
Release: 2016-06-23 13:46:25
Original
1848 people have browsed it

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

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;    }
Copy after login

GET调用:

 $url = "http://zhibo.fx678.com/index.php?page=htnews&ps=$size&time=$time"; GetWebFileStream($url);
Copy after login

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');
Copy after login
以上案例仅供参考,更多cUrl 知识点请参考php手册!



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