php中的file_get_contents或curl?

CJ7*_*CJ7 8 php curl file-get-contents

在PHP中使用file_get_contentscurl应该使用哪个来发出HTTP请求?

如果file_get_contents能完成这项工作,是否需要使用curl?使用curl似乎需要更多的线条.

例如:

卷曲:

$ch = curl_init('http://www.website.com/myfile.php'); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $content); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$output = curl_exec ($ch); 
curl_close ($ch); 
Run Code Online (Sandbox Code Playgroud)

的file_get_contents:

$output = file_get_contents('http://www.website.com/myfile.php'.$content); 
Run Code Online (Sandbox Code Playgroud)

Cod*_*uer 15

首先,cURL有很多选项可供选择.您可以真正设置所需的任何选项 - 许多支持的协议,文件上传,cookie,代理等.

file_get_contents() 真的只是GETs或POST文件并有结果.

但是:我尝试了一些API并做了一些"基准测试":

cURL 比 你的终端尝试它快得多file_get_contents
:time php curl.php

curl.php:

<?php 
$ch = curl_init();
$options = [
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL            => 'http://api.local/all'
];

curl_setopt_array($ch, $options);
$data = json_decode(curl_exec($ch));
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)

fgc.php

<?php 
$data = json_decode(file_get_contents('http://api.local/all'));
Run Code Online (Sandbox Code Playgroud)

平均cURL比file_get_contents我的情况快3-10倍.该api.local约600KB -一个缓存JSON文件responeded.

我不认为这是巧合 - 但你无法准确衡量,因为网络和响应时间差别很大,基于他们当前的负载/网络速度/响应时间等.(本地网络不会改变效果 - 也会有负载和流量)

但对于某些用例,它file_get_contents实际上也可能更快.


Vig*_*war 8

Curl比那更快File_get_contents.我刚刚做了一些快速的基准测试.

使用file_get_contents获取google.com (以秒为单位):

2.31319094 
2.30374217
2.21512604
3.30553889
2.30124092
Run Code Online (Sandbox Code Playgroud)

CURL采取:

0.68719101
0.64675593
0.64326 
0.81983113
0.63956594
Run Code Online (Sandbox Code Playgroud)


Wha*_*hen 3

供您参考,curl 可以让您有更多选项并使用 GET/POST 方法和发送参数。

并且file_get_contents将有更少的选项供您获取/发布参数。

希望这可以帮助...