PHP cache array of variables, in effect, is to write the array of PHP to a text file or a suffix called. php is stored, directly call this file when used. So how do you use PHP to save an array as a text-formatted file? Three ways to write a PHP array to a file to cache an array are shared below.
(1) using the PHP serialization function serialize and deserialization function unserialize you can store the array as a text file, and then deserialize it out as an array. PHP Code copy content to clipboard
- <?php
- $file ='./cache/phone.php ';
- $array =Array ('color ' = = 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) The self-created array is saved as a standard array format, although it is more complex to save, but simple to callPHP Code copy content to clipboard
- <?php
- $file ='./cache/phone.php ';
- $array =Array ('color ' = = 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)));
(3) using PHP's own function var_export can be stored in an array directly into a text file (recommended)PHP Code copy content to clipboard
- <?php
- $file ='./cache/phone.php ';
- $array =Array ('color ' = = Array ( ' Blue ',' red ',' green '),' size ' = = Array (' Small ',' Medium ',' large ');
- Cache
- $text =' <?php $rows = '. Var_export ($array, True).'; ';
- if (false!==fopen ($file,' w+ ')) {
- file_put_contents ($file,$text);
- }else{
- echo ' creation failed ';
- }
Through the above three methods, more commonly used should be the third and the first, we recommend the use of a third method, because convenient, simple, fast.
PHP's
1, PHP serialization serialize format of the detailed
2. PHP methods for serializing variables four ways to serialize variables
3, PHP to write large-scale website problem set
How does PHP save an array as a file? Three ways to quickly save an array as a file store