PHP: Store Array in File – Read / Write Arrays in File

by Yang Yang on December 22, 2011

You can save re-usable data in database such as MySQL so you can load them among different scripts / script sessions, though it may be a bit overwhelming for simple tasks because you have to set up a whole database and the connection credentials, etc.. File system is probably a better approach with regards to storing and retrieving simple tabular data, for not-so-important projects or test projects.

Then should we opt for XML or JSON? XML is bit too formal for teensy jobs. JSON, on the other hand, is the star of simplicity and capable or dealing with both tabular data and objects quite handily.

So we will store tabular data such as an PHP Array to JSON text which would then be stored as a ASCII text file. When we need to use the array again, be it in another PHP script or at a later time, we would just load the JSON string in the file and decode it into an array in PHP.

How can we do this? As simple as abc.

Store PHP Array in File

file_put_contents('array.txt', json_encode($your_array));

Read Array from File

$your_array = json_decode(file_get_contents('array.txt'), true);

Serialize()

Another approach is to use the serialize() and unserialize() functions of PHP. You may want to read this to choose between them: http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize

Comments on this entry are closed.

Previous post:

Next post: