D
D
dmitrypix2016-07-25 13:33:38
PHP
dmitrypix, 2016-07-25 13:33:38

How to cache json?

Tell me what's wrong?

$cached = fopen($cache_file, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush();

$file = 'site.com/json/liveu.json';

$cache_path = "/wp-content/tmp"; // папка с кэш-файлами на сервере
$cache_file = sprintf($file, $cache_path);
$cache_ttl = 900; // время жизни кэша в секундах
$html = ''; // HTML код для вставки на страницу

if( file_exists( $cache_file) && (time() - filemtime($cache_file)) < $cache_ttl) {
// берём кэшированные данные
$html = file_get_contents($file);
file_put_contents($cache_file, $html);
} 

echo $html;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2016-07-25
@alexey-m-ukolov

Everything is very, very bad.

  • What happens at the very beginning?
  • Why are you raping sprintf? Read the documentation for this function.
  • You have complete nonsense in checking the validity of the cache:
    если (файл_с_кешем_существует И кеш_не_протух)
        получить_данные_с_сайта
        записать_данные_в_кеш

Please note that you have nowhere to read from the cache (in the beginning, only some garbage associated with it).
Describe your task in simple words step by step, and then implement each step sequentially. Now you do not understand what is happening in the code, so it can only work for you by accident.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question