【问题标题】:Read online json file in faster way php以更快的方式读取在线 json 文件 php
【发布时间】:2012-04-09 15:20:39
【问题描述】:

我正在使用file_get_contents 读取在线json URL 我没有安装cURL 任何建议如何让我的请求更快

谢谢, 马里亚纳

【问题讨论】:

  • 可能是服务器响应慢?您可能对此无能为力。你能缓存数据,这样你就不必为每个请求进行外部调用了吗?

标签: php json curl file-get-contents


【解决方案1】:

做一些简单的基准测试:

<?php
$start = microtime(true);
for ($i=0;$i<=10;$i++){
    $handle = fopen("http://example.com/", "r");
    while (!feof($handle)) {
        $result .= fread($handle, 1024);
    }
    fclose($handle);
}
$end = microtime(true);
$time = $end - $start;

echo "Did fopen test in $time seconds<br />\n";
?> 

在 6.1602981090546 秒内进行了 fopen 测试

<?php
//file_get_contents is basically a wrapper for the above fopen so hence not much of a difference
$start = microtime(true);
for ($i=0;$i<=10;$i++){
    $result = file_get_contents('http://example.com');
}
$end = microtime(true);
$time = $end - $start;

echo "Did file_get_contents test in $time seconds<br />\n";
?>

是否在 6.5289459228516 秒内完成了 file_get_contents 测试

<?php
$start = microtime(true);
for ($i=0;$i<=10;$i++){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://example.com");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec($ch);
}
$end = microtime(true);
$time = $end - $start;

echo "Did cUrl test in $time seconds<br />\n";
?>

在 2.9657130241394 秒内完成 cUrl 测试

cURL 胜出...是时候寻找更好的主机了

【讨论】:

    【解决方案2】:

    无论哪种方式都应该很快。
    http://www.ebrueggeman.com/blog/php_benchmarking_fopen

    没有更好的。

    【讨论】:

      【解决方案3】:

      实际上没有办法让您的请求更快。如果数据变化不大,您可以做的是在本地缓存数据。

      伪代码:

      if (get_modification_time_of_file('cached.json') < time() - 300) {
          download_file()
      } else {
          read_locally()
      }
      

      【讨论】:

        【解决方案4】:

        你有两个选择。

        1:通过使用 fopen/file_get_contents 函数

        2:通过设置客户端桥并使用 AJAX 通过 POST 方法将其发送到 php。然后使用 json_decode 在 PHP 上获取它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-19
          • 1970-01-01
          • 1970-01-01
          • 2016-03-02
          • 1970-01-01
          • 2016-02-29
          相关资源
          最近更新 更多