繁体   English   中英

php中的file_get_contents或curl?

[英]file_get_contents or curl in php?

在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); 

的file_get_contents:

$output = file_get_contents('http://www.website.com/myfile.php'.$content); 

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

file_get_contents()实际上只是GET或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);

fgc.php

<?php 
$data = json_decode(file_get_contents('http://api.local/all'));

在我的情况下,平均cURL比file_get_contents快3-10倍。 api.local用缓存的JSON文件重新发送 - 大约600kb。

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

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

CurlFile_get_contents快。 我刚刚做了一些快速的基准测试。

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

2.31319094 
2.30374217
2.21512604
3.30553889
2.30124092

CURL采取:

0.68719101
0.64675593
0.64326 
0.81983113
0.63956594

为了您的信息,curl可以让你有更多的选择,并使用GET / POST方法和发送参数。

file_get_contents对于GET / POST参数的选项较少。

希望这可以帮助...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM