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

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数