我从天气api中提取数据,只想让你每隔十分钟从api中拉出一次,所以我想我会把json字符串保存到一个文件并保存拉到文件的时间所以我可以将当前时间与最后一次拉动时间进行比较,然后从文件或api中提取数据。 if语句似乎工作得很好。当diff超过600时,它会从api中提取数据并显示数据,但是当diff小于600时,数组似乎不一样......
任何见解都会非常感激!
function get_weather_data() {
//define filepath to save/read/write weather data
$weatherData = "";
$weatherDataFile = "assets/docs/weather.json";
//define filepath to save/read/write last api call time
$prevTimeFile = "assets/docs/prevtime.txt";
$prevTime = file_get_contents($prevTimeFile);
$currTime = time();
$diff = ($currTime - $prevTime);
//If diff is longer than 10 mins (600 secs) then pull from api
if ($diff < 600) { //get weather data from file
$weatherData = file_get_contents($weatherDataFile);
}
else { //get weather data from api
$request = ('http://api.openweathermap.org/data/2.5/forecast/city?id=4699066&APPID=xxxxxxxxxxxxxxxxxx');
$weatherData = file_get_contents($request);
//save api data back to weatherData file
$wFile = fopen($weatherDataFile, "cb");
fwrite($wFile, $weatherData);
fclose($wFile);
//save current time of data to prevTimeFile
$tFile = fopen($prevTimeFile, "cb");
fwrite($tFile, time() );
fclose($tFile);
}
$weather = json_decode($weatherData, true);
echo $diff;
echo $weather['city']['name'];
}