php中的file_get_contents或curl? [英] file_get_contents or curl in php?

查看:32
本文介绍了php中的file_get_contents或curl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which of file_get_contents or curl should be used in PHP to make an HTTP request?

如果file_get_contents 可以完成这项工作,是否还需要使用curl?使用 curl 似乎需要更多行.

If file_get_contents will do the job, is there any need to use curl? Using curl seems to need more lines.

例如:

卷曲:

$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 有很多选项可以设置.您真的可以设置您需要的任何选项 - 许多支持的协议、文件上传、cookies、代理等等.

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() 实际上只是 GET 或 POST 文件并有结果.

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

然而:我尝试了一些 API 并做了一些基准测试":

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

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

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

就我而言,平均 cURL 比 file_get_contents 快 3-10 倍.api.local 响应缓存的 JSON 文件 - 大约 600kb.

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)

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

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

所以我构建了一个简单的函数:https://git.io/J6s9e

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

这篇关于php中的file_get_contents或curl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆