如何在php脚本中添加缓存?

时间:2017-08-26 07:59:30

标签: php html api

有一个脚本(我在网站8上有这样的脚本)

<?php

    $map = function($array, $from, $to){
        $result = [];
        if(!empty($array) && is_array($array)){
            foreach ($array as $element) {
                $key = $element[$from]?:null;
                $value = $element[$to]?:null;
                if($key && $value){
                    $result[$key] = $value;
                }
            }
        }
        return $result;
    };

   $airlines = $map(json_decode(file_get_contents('http://aviaciya.com/json/airlines.json'), true), 'iata', 'name');
$cit=json_decode(file_get_contents("http://avia-avia.ru/json/cities.json")); $cities=array(); foreach($cit as $val) { if(property_exists($val->name_translations,"ru")) $cities[$val->code]=$val->name_translations->ru;}

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.travelpayouts.com/v1/prices/cheap?origin=MOW&destination=AER&limit=30&token=**************");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Access-Token: *************"));
    $response = curl_exec($ch);
    curl_close($ch);
    $products=json_decode($response,true);
    $replace_value = function($key, $val) use ($cities, $airlines){
        $response = $val;
        switch($key){case 'destination':
                $response = $cities[$val];break;
                case 'origin':
                $response = $cities[$val];break;
            case 'airline':
                $response = $airlines[$val];
                break;
        }
        return $response;
    }

    ?>








    <div id="kurorty" class="container-fluid">

     <div class="table-responsive"><h5>Авиабилеты Москва Адлер</h5><table class="table table-hover">
        <thead>
          <tr>
            <th style="text-align: center;"> Пункт отправления</th>
            <th style="text-align: center;">Пункт назначения </th>
            <th class="mob" style="text-align: center;"> Авиакомпания</th> <th style="text-align: center;">Цена, р.</th> <th class="mob" style="text-align: center;">Дата вылета</th>
    <th class="mob" style="text-align: center;">Обратная дата</th>
    <th> </th>
          </tr>
        </thead>    <tbody>
    <?php
    if(isset($products['data']) && is_array($products['data'])) {
    foreach ($products['data'] as $key => $data) {
    foreach ($data as $destination => $row) {
    if (preg_match('/[A-Z]{3}/i', $key)) {
    ?>
    <tr>
    <td>&nbsp; <?php echo Москва ;?>&nbsp;</td>
            <td>&nbsp; <?= $replace_value('destination',$key) ? $replace_value('destination', $key) : "<b>" .'Обновл.'. "</b>"; ?>&nbsp; </td>

         <td class="mob"><img height="50" alt="" width="120" src="http://pics.avs.io/180/70/<?= $row['airline']?>.png" /></td>
    <td><?php echo $replace_value('price', $row['price']); ?>&nbsp;  RUB &nbsp; </td> 
    <td class="mob"><?php echo $replace_value('departure_at', substr($row['departure_at'], 0, 10)); ?></td>
    <td class="mob"><?php echo $replace_value('return_at', substr($row['return_at'], 0, 10)); ?></td>
          <td><a rel="nofollow" role="button" alt="авиабилеты Москва <?php echo $replace_value('destination',$key); ?>" title="авиабилеты Москва <?php echo $replace_value('destination',$key); ?>" href="https://bilety.avia-avia.ru/flights/?origin_iata=MOW&destination_iata=<?=$key?>&depart_date=<?=substr($row['departure_at'], 0, 10)?>&return_date=<?=substr($row['return_at'], 0, 10)?>&adults=1&children=0&infants=0&trip_class=0&marker=87111&with_request=true">Поиск</a></td></tr>
    <?php
    }
    }
    }
    }
    ?>  </tbody>
      </table>
    </div>

在后续脚本中,我不再使用此行了

$airlines = $map(json_decode(file_get_contents('http://aviaciya.com/json/airlines.json'), true), 'iata', 'name');
$cit=json_decode(file_get_contents("http://avia-avia.ru/json/cities.json")); $cities=array(); foreach($cit as $val) { if(property_exists($val->name_translations,"ru")) $cities[$val->code]=$val->name_translations->ru;}

这是一个好人写给我的意思:

  

&#34;脚本非常简单,你拿json并保存它,有一个   用于纠正脚本的几行,并且在您的代码中只有   需要更改网址。&#34;这个想法是你需要节省$   产品到文件并从该文件中读取。 &#34;

一切都是如此简单,只为了我,它是一个嘎嘎作响的森林。&#34;请帮忙,我的手已经掉下来了。

非常感谢您的帮助,非常尊重。

1 个答案:

答案 0 :(得分:1)

Voilà,将其添加到脚本的头部

/**
 * Function to get cacheFile
 * @param $srcfile
 * @return string
 */
function cacheFile($srcfile)
{
    /* Defintions */
    /**
     * string Cachepath is the path to your www-user writeable directory, this can be relative or absolute
     */
    $cachePath = './';


    /**
     * array srcfiles, key is Identifier and value is the full link to the json file
     */
    $srcfiles = [
        'airline' => 'http://aviaciya.com/json/airlines.json',
        'cities' => 'http://avia-avia.ru/json/cities.json'
    ];


    /**
     * Autogenerated from cachePath and srcfiles
     */
    $cacheFile = $cachePath.end(explode("/", $srcfiles[$srcfile]));


    /**
     * int Time in seconds for cache
     */
    $cachingTime = 600;


    /**
     * @param $cacheFile
     * @param $url
     */
    $downloader = function($cacheFile, $url) {
        file_put_contents($cacheFile,file_get_contents($url));
    };

    /* CreateCache File if it doesnt exists */
    if(!file_exists($cacheFile) || time() - filemtime($cacheFile) > $cachingTime) {
        $downloader($cacheFile, $srcfiles[$srcfile]);
    }

    return $cacheFile;
}

然后你可以调用这个加载器,而不是将fqdn提供给file_get_contents函数,就像这样......

$airlines = map(json_decode(file_get_contents(cacheFile('airline')), true), 'iata', 'name');
$cit=json_decode(file_get_contents(cacheFile('cities'))); $cities=array(); foreach($cit as $val) { if(property_exists($val->name_translations,"ru")) $cities[$val->code]=$val->name_translations->ru;}

更新

  • 更好的下载功能(仅限cacheFile和URL作为参数)
  • 文件存在和filemtimecheck一次