使用到期日期在服务器上缓存JSON?

问题描述 投票:-3回答:2

这是我编写的一些工作代码,用于调用JSON文件并将其缓存在我的服务器上。

我正在调用缓存的文件。如果文件存在,我使用json_decode。如果文件不存在,我然后调用JSON并解码它。然后在调用JSON url之后,我将内容写入缓存的文件url。

$cache = @file_get_contents('cache/'.$filename.'.txt');

 //check to see if file exists:
if (strlen($cache)<1) {

    // file is empty
    echo '<notcached />';
    $JSON1= @file_get_contents($url);

    $JSON_Data1 = json_decode($JSON1);

    $myfile = fopen('cache/'.$filename.'.txt', "w");
    $put = file_put_contents('cache/'.$filename.'.txt', ($JSON1));

} else {

    //if file doesn't exist:
    $JSON_Data1 = json_decode($cache);
    echo '<cached />';
}

有没有一种方法可以检查$ filename.txt的年龄,如果超过30天,可以在else语句中获取JSON url?

php json file-get-contents file-put-contents cache-expiration
2个回答
2
投票

你可以使用类似的东西

if (strlen($cache)<1) {

$file = 'cache/'.$filename.'.txt'; $modify = filemtime($file); //check to see if file exists: if ($modify == false || $modify < strtotime('now -30 day')) { // file is empty, or too old echo '<notcached />'; } else { // Good to use file echo '<cached />'; } 返回文件的最后修改时间,if语句检查文件是否存在(filemtime()如果失败则返回false)或文件上次修改超过30天前。

或者......检查文件是否存在或过旧(没有警告)

filemtime

2
投票

我在之前的项目中使用了一个简单的文件缓存类,我认为这应该可以帮到你。我认为这很容易理解,缓存时间以秒为单位,$file = 'cache/'.$filename.'.txt'; if (file_exists($file) == false || filemtime($file) < strtotime('now -30 day')) { // file is empty, or too old echo '<notcached />'; } else { // Good to use file echo '<cached />'; } 函数清除文件名,以防它包含无效字符。

setFilename

它可以像这样使用。

<?php

class SimpleFileCache
{
    var $cache_path = 'cache/';
    var $cache_time = 3600;
    var $cache_file;

    function __construct($name)
    {
        $this->setFilename($name);
    }

    function getFilename()
    {
        return $this->cache_file;
    }

    function setFilename($name)
    {
        $this->cache_file = $this->cache_path . preg_replace('/[^0-9a-z\.\_\-]/', '', strtolower($name));
    }

    function isCached()
    {
        return (file_exists($this->cache_file) && (filemtime($this->cache_file) + $this->cache_time >= time()));
    }

    function getData()
    {
        return file_get_contents($this->cache_file);
    }

    function setData($data)
    {
        if (!empty($data)) {
            return file_put_contents($this->cache_file, $data) > 0;
        }
        return false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.