Follow me on Twitter RSS FEED

PHP serialization

Recently, I was working on a PHP script for my Dad which reads some data, and will make a report on the changes of the data over time. To save the reports, I needed some way to export an array into a file and then read it back from the file in a separate script and have it exactly the same.

Thats what the serialize function does in PHP. It takes any argument, and converts it to a string. Then you can unserialize the string, and get your original object. So I just serialized my array and saved it to a file:


$string = serialize($array);
file_put_contents("saved_data.txt");


and saved it to a text document, and when I wanted to access the data:


unserialize(file_get_contents("saved_data.txt"));


If you have more than one object you want to serialize, you can put all of it in an array, and serialize the array.


$string_1 = "Hello World";
$string_2 = "What are you doing?";
$string_12 = serialize(array($string_1,$string_2))

0 comments:

Post a Comment