Encapsulating Complex Data Types in String

You want to a string representation of an array or object for storage in a file or database.

Posted on February 12, 2015 in PHP

Use Serialize() to encode variables and their values into a textual form:

$pantry = array('sugar'=>'2 lbs.', 'butter'=' 3 sticks');
$fp = fopen('/tmp/pantry', 'w') or die("Can't open pantry");
fputs($fp, serialize($pantry));

To re-create the variables, use unserialize():

$new_pantry = unserialize('file_get_contents('/tmp/pantry'));

comments powered by Disqus