使用循环创建缓存文件

时间:2019-01-26 03:05:44

标签: php

我有一个脚本,可以从Json文件中收集多个城市的天气数据(每个城市都有Json的唯一URL)
一切正常,如此处所示:
1http://meteocaldas.com/previsao2.php
不过,此示例仅适用于3个城市,我想将其扩展到40个城市,因此我需要创建40个缓存文件,以不超过允许的最大请求数。
我是一个初学者,而我能做到这一点的唯一方法是通过逐个创建缓存文件,正如您在脚本中看到的那样。我尝试了几种解决方案,使之使用for($ x = 0; $ x <$ arrlength; $ x ++)等循环创建缓存文件,但结果始终是错误消息:-)
有没有一种简单的方法可以在此脚本中循环以创建从city [0]到city [n]的缓存文件?
预先感谢您的帮助!

### 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]) 

1 个答案:

答案 0 :(得分:0)

请不要使用城市名称作为select中的值,而应使用数组索引。通过允许$city作为城市数组的索引,可以简化代码。然后,您可以对缓存代码采取类似的方法,使用城市名称(= $arr[$city])生成缓存文件名和要提取的URL:

$arr = ["city0", "city1", "city2" ];
$city = isset($_POST['city']) ? $_POST['city'] : 0;
?>
    <form name="f" id="a" method="post" action="">
    <select id="city" name="city" onchange="this.form.submit()" >                      
<?php
foreach ($arr as $k => $v) {
    echo "<option value='$k'" . ($k == $city ? " selected" : "") . ">$v</option>\n";
}
?>
   </select>
   </form>
<?php
// create URL
$city_name = $arr[$city];
$fIOURL = "http://www.{$city_name}.com";
// check cache
$city_cache = "cache/{$city_name}.txt";
$cache_exists = file_exists($city_cache);
if (!$cache_exists || time() - filemtime($city_cache) > 60 * 60) { 
    // cache doesn't exist, or is no longer valid
    $rawData = file_get_contents($fIOURL);
    if ($rawData != "") {
        // if we successfully fetched data, recreate the cache
        $cache_exists = file_put_contents($city_cache, $rawData);
    }
}
if ($cache_exists) {
    // fetch the data (either cached or freshly loaded) from the cache file
    $rawData = file_get_contents($city_cache);
    $forecastLoadedTime = filemtime($city_cache);
}
else {
    // some sort of error message here
    $rawData = "No data available for $city_name!";
}
$decoded = json_decode($rawData, true); 

更新

由于您的API URL都是基于依赖于城市的数字,因此生成它们的最简单方法是更改​​要由该数字索引的城市名称数组。因此,您可以将上面的前两行代码更改为:

$arr = array(31927 => "city0", 16765 => "city1", 29832 => "city2");
$city = isset($_POST['city']) ? $_POST['city'] : array_keys($arr)[0];

请注意,我们现在将默认城市作为数组中的第一个键(在此示例数据中为31927)。然后,您可以将URL生成代码更改为:

$fIOURL = "http://wwwsite/index.php?api_lang=pt&localidad={$city}&affiliate_id=xxxx&v=3.0";