I have a script to gather weather data for several cities from Json files (each city has a unique url for the Json)
Everything is working perfectly as it can be seen here:
1: http://meteocaldas.com/previsao2.php
However this example is just for 3 cities and I want to extend it to 40 cities so I need to create 40 cache files in order not to exceed maximum allowed requests.
I am a begginer and the only way i could get this to work was by creating cache files one by one as you can see in the script. I tried several solutions to make a loop to create the cache files using things like for($x = 0; $x < $arrlength; $x++) etc, but results were always error messages :-)
Is there an easy way to make a loop in this script to create cache files from city[0] to city[n]?
Thanks in advance for any help!
### Create drop down menu and array with cities
<?php
$arr = ["city0", "city1", "city2" ];
$city = $arr[0];
if( $_POST['city']){
$city=$_POST['city'];
}
?>
<form name="f" id="a" method="post" action="">
<select id="city" name="city" onchange="this.form.submit()" >
<?php
foreach ($arr as $a){
if($a == $city){
echo "<option value='{$a}' selected >$a</option>";
}else{
echo "<option value='{$a}' >$a</option>";
}} ?>
</select>
</form>
### URL's for 5 day forecast's JSON for each city
if ($city == $arr[0]) {$fIOURL = "http://www.city0.com" ;}
elseif ($city == $arr[1]) {$fIOURL = "http://www.city1.com" ;}
elseif ($city == $arr[2]) {$fIOURL = "http://www.city2.com" ;}
### CACHE City0 ###
if ($city == $arr[0]) {
if(file_exists('cache/'.$arr[0].'.txt')){
if (time()-filemtime('cache/'.$arr[0].'.txt') > 60 * 60) {
unlink('cache/'.$arr[0].'.txt');
}
}
if(file_exists('cache/'.$arr[0].'.txt')){
$rawData = file_get_contents('cache/'.$arr[0].'.txt');
$forecastLoadedTime = filemtime('cache/'.$arr[0].'.txt');
}
else{
$rawData = file_get_contents($fIOURL);
if($rawData!=""){
file_put_contents('cache/'.$arr[0].'.txt',$rawData);
}
$forecastLoadedTime = time();
}
$rawData = file_get_contents('cache/'.$arr[0].'.txt');
$decoded = json_decode($rawData, true);
}
### CACHE City1 (repeat process above but for $arr[1]###
if ($city == $arr[1]) {
if(file_exists('cache/'.$arr[1].'.txt')){
if (time()-filemtime('cache/'.$arr[1].'.txt') > 60 * 60) {
unlink('cache/'.$arr[1].'.txt');
}
}
if(file_exists('cache/'.$arr[1].'.txt')){
$rawData = file_get_contents('cache/'.$arr[1].'.txt');
$forecastLoadedTime = filemtime('cache/'.$arr[1].'.txt');
}
else{
$rawData = file_get_contents($fIOURL);
if($rawData!=""){
file_put_contents('cache/'.$arr[1].'.txt',$rawData);
}
$forecastLoadedTime = time();
}
$rawData = file_get_contents('cache/'.$arr[1].'.txt');
$decoded = json_decode($rawData, true);
}
### CACHE City2 ###
(repeat process but now with $arr[2])