11

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

文件获取内容:

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

3 回答 3

17

First of all cURL has a lot of options to set. You can really set any option you need to - many supported protocols, file-uploads, cookies, proxies and more.

file_get_contents() really just GETs or POSTs the file and has the result.

However: I tried some APIs and did some "benchmarking":

cURL was a lot faster than file_get_contents
Just try it with your terminal: 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'));

Averaged cURL was 3-10 times faster than file_get_contents in my case. The api.local responeded with a cached JSON file - about 600kb.

I don't think it was coincidence - But that you can't measure this accurately, because the network and the response times differ a lot, based on their current load / network speed / response times etc. (local networks won't change the effect - there will be load & traffic too)

But for certain use cases, it could also be that file_get_contents is actually quicker.

So I built a simple function: https://git.io/J6s9e

于 2014-07-25T11:05:33.580 回答
8

Curl然后更快File_get_contents。我只是对此做了一些快速的基准测试。

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

2.31319094 
2.30374217
2.21512604
3.30553889
2.30124092

卷曲采取:

0.68719101
0.64675593
0.64326 
0.81983113
0.63956594
于 2016-04-08T08:09:02.823 回答
2

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

并且file_get_contents将为您提供较少的 GET/POST 参数选项。

希望这可以帮助...

于 2012-10-22T06:27:50.177 回答