dongleman4760 2019-01-26 03:05
浏览 72
已采纳

使用循环创建缓存文件

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]) 
  • 写回答

1条回答 默认 最新

  • doutui4649 2019-01-26 03:35
    关注

    Rather than using the name of the city as the value in your select, use the array index instead. This will simplify your code by allowing $city to be an index into the array of cities. Then you can take a similar approach to your caching code, using the city name (= $arr[$city]) to generate the cache file name and the URL for fetching:

    $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>
    ";
    }
    ?>
       </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); 
    

    Update

    Since your API URLs are all based on a number that is dependent on the city, the simplest way to generate them is to change your array of city names to be indexed by that number. So you would change the first two lines of code above to something like:

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

    Note that we now get the default city as the first key in the array (with this example data it would be 31927). Then you would change the URL generation code to:

    $fIOURL = "http://wwwsite/index.php?api_lang=pt&localidad={$city}&affiliate_id=xxxx&v=3.0";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?