Dave's Brain

Browse - Programming Tips - php: how can I save (persist) an object to a file?

Date: 2018mar31
Language: php
Keywords: disk,persistence,store,restore,state

Q. php: how can I save (persist) an object to a file?

A.  Use serialize() and unserialize() like this.

function serializeToFile(&$a, $out_file_final) { if (!file_put_contents($out_file_tmp, serialize($a))) { print "Could not save to $out_file_tmp\n"; return; } if (file_exists($out_file_final)) { copy($out_file_final, "$out_file_final.old"); # Ignore error } if (!rename($out_file_tmp, $out_file_final)) { print "Could not rename to $out_file_final\n"; return; } print "Save to $out_file_final ok\n"; } function unserializeFromFile($serial_file) { if (($ser = file_get_contents($serial_file)) == false) return false; return unserialize($ser); }
Its fast and I like that the serialized format is human-friendly text.

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.