cURL加载时间过长 [英] cURL takes too long to load

查看:707
本文介绍了cURL加载时间过长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用cURL调用PHP中的REST端点来获取一些JSON数据:

I am calling a REST endpoint in PHP using cURL to fetch some JSON data:

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

echo $result;

curl_close($ch);

使用上述代码在localhost上获取数据需要2.5秒。在活动服务器上运行时,相同的代码大约需要7.5秒。当URL在浏览器上直接打开时,只需要1.5秒。

It takes 2.5 seconds to fetch the data using the above code on my localhost. The same code takes around 7.5 seconds when run on the live server. When the URL is opened directly on a browser it takes only 1.5 seconds.

我的问题是:为什么cURL需要这么长时间来获取实时服务器上的数据

My question is: Why does it take so long for cURL to fetch data on the live server and how can I solve this problem?

下面是服务器上 curl_getinfo($ ch)的输出:

Below is the output of curl_getinfo($ch) on the server:

Array
(
    [content_type] => application/json
    [http_code] => 200
    [header_size] => 420
    [request_size] => 113
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 7.305496
    [namelookup_time] => 0.150378
    [connect_time] => 0.473187
    [pretransfer_time] => 0.473237
    [size_upload] => 0
    [size_download] => 1291504
    [speed_download] => 176785
    [speed_upload] => 0
    [download_content_length] => -1
    [upload_content_length] => 0
    [starttransfer_time] => 1.787901
    [redirect_time] => 0
    [redirect_url] => 
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_port] => 53962
)


推荐答案

我的问题。正如我在问题中提到的,该服务加载了最快的浏览器。因此,我在Google Chrome浏览器的网络标签中查看了请求的请求标头。我复制了这些头,并在PHP中的我的cURL请求中使用它们。在删除这些头后,我发现我需要做的是添加一个 Accept-Encoding 头。我通过了 gzip 的值:

I found the solution to my problem. As I had mentioned in the question, the service was loading the fastest in browsers. So, I checked the 'Request Headers' of the request in the 'Network' tab of Google Chrome Inspector. I copied those headers and used them in my cURL request in PHP. After scraping those headers I found that all I needed to do was to add an Accept-Encoding header. I passed a value of gzip like so:

curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

但是将其设置为空字符串也可以。

but setting it to an empty string also works.

curl_setopt($ch, CURLOPT_ENCODING, '');

根据 php.net manual for CURLOPT_ENCODING:

According to the php.net manual for CURLOPT_ENCODING:


Accept-Encoding:头。这使得解码
的响应。支持的编码是identity,deflate和
gzip。如果设置了空字符串,则会发送包含所有
支持的编码类型的标头。

The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent.

这篇关于cURL加载时间过长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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