Php cache array to file

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Simple file-based cache system for PHP

License

idct-tech/php-array-file-cache

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Simple file-based caching system for PHP which allows storing and retrieval of data in and from files using a simple array interface.

use IDCT\FileArrayCache; $cache = new FileArrayCache("/tmp"); //saving: $yourData = ['value_int' => 1, 'value_string' => 'test']; $cache["myCacheKey"] = $yourData; //reading: $data = $cache["myCacheKey"];

To clear all entries in cache, but keep the folder and config use clearCache() method.

In case you do not use any package manager in your code then be sure to include all classes and interfaces.

Suggested way is to use Composer[https://getcomposer.org/] and install the library in your project using:

composer require idct/php-array-file-cache

Create an instance of FileArrayCache by calling its constructor. One parameter is mandatory:

  • $cachePath which must point to a writable and readable directory where cache will be or is stored. Warning: if a cache with cache_config file (after version 0.2) exists already in the folder then initialization will be verified with it: failure will throw a LogicException .
  • int $levels : Amount of subfolder levels used to limit files count in a single folder. Defaults to 2.
  • IHashAlgo $hashAlgo : Algorithm used to build the filename: a hash out of the given key. Must implement IHashAlgo . Defaults to Md5 .
  • ICodec $codec : Encoder / decoder which converts provided objects into strings (and the other way around) stored in files. Defaults to JsonCodec .

To contribute please just file an issue or merge request (pull request). Whenever possible please try to keep backwards-compatiblity.

Be sure to follow latest coding standards!

About

Simple file-based cache system for PHP

Источник

PHP to store arrays as text file methods summarize _php Tips

A variable in the form of a PHP cache array, in effect, is simply to write the array to a text file or a suffix named. php to store it, and call this file directly when used. So how do you use PHP to save the array as a text-formatted file? Here’s a three-way implementation that writes a PHP array to a file to cache the array.
(1) using Serialize to store array serialization as a text file, and then use Unserialize to restore

 array (' Blue ', ' red ', ' green '), ' size ' => array (' small ', ' medium ', ' large ')); Cache if (False!==fopen ($file, ' w+ ')) < file_put_contents ($file, serialize ($array));/write Cache >//read out cache $handle =fopen ($file, ' R '); $cacheArray =unserialize (Fread ($handle, FileSize ($file));

(2) Self-created to save the array as a standard array format, although the save time is complex, but the call is simple

 array (' Blue ', ' red ', ' green '), ' size ' => array (' small ', ' medium ', ' large ')); Cache_write ($file, $array, ' rows ', false); Write function Cache_write ($filename, $values, $var = ' rows ', $format =false) //array converts to String function Arrayeval ($array, $format =false, $level =0) $line = "\ n"; $evaluate = ' Array '. $line. $space. ' ('. $line; $comma = $space; foreach ($array as $key => $val) 12)? ' \ addcslashes ($val, ' \ \ \ \ \]. \ ': $val; if (Is_array ($val)) '. Arrayeval ($val, $format, $level + 1); >else < $evaluate. = $comma. $key. ' =>'. $val; $comma = ', '. $line $space; $evaluate. = $line. $space. ') '; return $evaluate; //write File function WriteFile ($filename, $writetext, $openmod = ' W ') else >

(3) store the array in a text file directly by using Var_export

 array (' Blue ', ' red ', ' green '), ' size ' => array (' small ', ' medium ', ' large ')); Cache $text = ' else< echo ' Create failure ';

The above is for you to introduce three kinds of PHP to save the array as a text format method, I hope to help you learn.

This article is an English version of an article which is originally in the Chinese language on aliyun.com and is provided for information purposes only. This website makes no representation or warranty of any kind, either expressed or implied, as to the accuracy, completeness ownership or reliability of the article or any translations thereof. If you have any concerns or complaints relating to the article, please send an email, providing a detailed description of the concern or complaint, to info-contact@alibabacloud.com. A staff member will contact you within 5 working days. Once verified, infringing content will be removed immediately.

Источник

Saving a PHP array to a text file.

This is a tutorial on how to save a PHP array to a text file.

In this tutorial, we will also show you how to read the file in question.

There are two ways of doing this. One involves encoding the array into a JSON format. The other involves the serialize function, which will basically creates a storable representation of a PHP value (in this case, our array).

JSON.

To save a PHP array to a text file using the JSON functions, we can take the following steps.

  1. Encode the array into a JSON string using json_encode.
  2. Save the JSON string to the text file in question.
  3. If we want to load the JSON string from our text file, then we can use the file_get_contents function.
  4. Finally, we can decode the JSON string back into an array by using the json_decode function.

Take a look at the following example.

//Example array. $array = array('Ireland', 'England', 'Wales', 'Northern Ireland', 'Scotland'); //Encode the array into a JSON string. $encodedString = json_encode($array); //Save the JSON string to a text file. file_put_contents('json_array.txt', $encodedString); //Retrieve the data from our text file. $fileContents = file_get_contents('json_array.txt'); //Convert the JSON string back into an array. $decoded = json_decode($fileContents, true); //The end result. var_dump($decoded);

Personally, I prefer the method above, simply because the file size will be smaller and JSON is a far more portable format.

Serialized Data

Using the serialize method, we can take the following steps.

  1. The array is serialized into “storable” string. This string represents the structure of our array.
  2. We save the serialized string to the text file in question.
  3. As soon as we want to load the serialized string, we use the file_get_contents function.
  4. We then convert the string back into an array using the unserialize function.

A code example, using the serialize method.

Note that you can also use this method to store PHP arrays in databases and whatnot.

Источник

Кэширование контента в файлы PHP

Кэширование контента в файлы PHP

Для ускорения работы PHP-сайта можно применить механизм единоразового сохранения сформированного контента в файлах кэша для их повторного использования, например меню сайта, «тяжелый» вывод выгрузки из базы данных и т.д. Для этих целей был написан небольшой статический PHP-класс для кэширования блоков контента или страниц целиком основанный на буферизации вывода в переменную.

Код файла cache.php

 else < self::$keys[] = $name; return false; >> else < return ''; >> /** * Отправка данных в кэш. */ public static function set($content) < if (self::$enable) < $name = array_pop(self::$keys); $dir = __DIR__ . self::$path . '/'; if (!is_dir($dir)) < @mkdir($dir, 0777, true); >file_put_contents($dir . '/' . $name . '.tmp', $content); > return $content; > /** * Начало кэширования фрагмента. */ public static function begin($name) < if ($content = self::get($name)) < echo $content; return false; >else < ob_start(); return true; >> /** * Завершение кэширования фрагмента. */ public static function end() < echo self::set(ob_get_clean()); >/** * Очистка кэша. */ public static function clear() < $dir = __DIR__ . self::$path; foreach (glob($dir . '/*') as $file) < if (is_file($file)) < unlink($file); >> > >

Использование

// Подключаем файл класса require_once '/cache.php'; // Кэшируем фрагмент кода if (Cache::begin('test')) < ?>

Теперь, если в папке cache нет файла test.tmp, то условие выполнится, контент выведется и сохранится в файле. В другом случаи контент всегда будет выводится из файла кэша.

Источник

Читайте также:  Listing numbers in python
Оцените статью