Generate php source code based on php array

I have a non-modifiable function that takes a few seconds. The function returns an array of objects. The result changes only once a day.

To speed things up, I wanted to cache the result using APC, but the hosting provider (shared hosting environment) does not offer any memory caching solutions (APC, memcache, ...).

The only solution I found was to use serialize () to store the data in a file and then deserialize the data back.

How about generating php source code from an array? Later I could just call

require data.php 

to get data into a predefined variable.

Thanks!

UPDATE: saving the resulting .html is not an option, because the output is user dependent.

+4
source share
3 answers

Do you mean something like this?

 // File: data.php <?php return array( 32, 42 ); // Another file $result = include 'data.php'; var_dump($result); 

It is already possible. To update the file, you can use something like this

 file_put_contents('data.php', '<?php return ' . var_export($array, true) . ';'); 

Update: However, there is nothing wrong with serialize () / unserialize () and saving a serialized array to a file.

+6
source

Why not just cache the resulting html page that is generated? You can do this quite simply:

 // Check to see if cached file exists // You could run a crob job to delete this at a certain time // or have the cache file expire after a set amount of time if(file_exists('cache.html')) { include('cache.html'); exit; } ob_start(); // start capturing output buffer // do output $output = ob_get_contents(); $handle = fopen('cache.html', 'w'); fwrite($handle, $output); fclose($handle); ob_end_flush(); 
+2
source

You can simply write the answers to the database and use the function arguments as the key.

0
source

Source: https://habr.com/ru/post/1345890/


All Articles