Nxlevel Nxlevel - 3 months ago 13
JSON Question

Copy external json data and paste in local json file

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}

Answer

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