doumangzhen7204 2016-09-06 16:49
浏览 307
已采纳

复制外部json数据并粘贴到本地json文件中

I have a bunch of widgets on my admin interface one of which is weather. Based on how my admin interface is coded it reloads every 60sec. Which is too many api calls per minute for weather. To change only the weather widget refresh rate is gonna take a lot, so thought it would be easier if i copy the data from the openweathermap.org every 60min and place the data in a local json that can be accessed by my weatehr widget instead of making so many api calls to the external source.

How can i use jquery, javascript or php to copy data looking like the following,from a website address to a local JSON file?

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":296.2,"pressure":1023,"humidity":69,"temp_min":294.82,"temp_max":297.15},"wind":{"speed":1.5},"clouds":{"all":75},"dt":1473178865,"sys":{"type":1,"id":5091,"message":0.0074,"country":"GB","sunrise":1473139361,"sunset":1473186795},"id":2643743,"name":"London","cod":200}
  • 写回答

2条回答 默认 最新

  • dongmu2026 2016-09-06 17:05
    关注

    I recommended you to create a scheduled task that run every 60s to get the weather data via the api, then store the data into a local file and redirect the admin interface to read from that file, not the api

    You can use cron jobs to create a scheduled task for retrieving the data from the api.

    here is a sample code for retrieving the weather data from the api using PHP and store the result to a text file.

    <?php
    
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=79191467e423ba376b1b72529788eeb8",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
    
      $weather_data = ($response);
      // save $weather_data to local file
      $file = 'weather_data.txt';
    
      // Write the contents to the file
      file_put_contents($file, $weather_data);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程