Persist PHP arrays to disk


Greg @ Red Tuque

Suprisingly there are times when a database is not available to persist a data structure through the script’s life cycles. Thankfully PHP has a cool and easy way to serialize/unserialize an array such that I can be stored in a file on disk.

To serialize an array simply call the serialize function and pass in the desired data structure as an argument. In return PHP will spit out an encoded version as a string, which then can be written to file.

$s = serialize($registered);
ftruncate($handle, 0);
fseek($handle, 0);
fwrite($handle, $s);

To recover the data into an array simply unserialize the contents of the file.

if (file_exists(FILE)) { 
	$handle = fopen(FILE,'r+') or die("ERROR: Cannot open file.");
	$s = fread($handle, filesize(FILE));
} 
$registered = unserialize($s);

This method would also work for non file I/O, but rather NIO to transfer the data over the wire. But this day and age you might as…

View original post 8 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s