Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php how to serialize array of objects?

I have small class called 'Call' and I need to store these calls into a flat file. I've made another class called 'CallStorage' which contains an array where I put these calls into.

My problem is that I would like to store this array to disk so I could later read it back and get the calls from that array.

I've tried to achieve this using serialize() and unserialize() but these seems to act somehow strange and part of the information gets lost.

This is what I'm doing:

//write array to disk
$filename = $path . 'calls-' . $today;
$serialized = serialize($this->array);
$fp = fopen($filename, 'a');
fwrite($fp, $serialized);
fclose($fp);

//read array from serialized file

$filename = $path . 'calls-' . $today;
if (file_exists($filename)) {
    $handle = fopen($filename, 'r');
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    $unserialized = unserialize($contents);
    $this->setArray($unserialized);
}

Can someone see what I'm doing wrong, or what. I've also tried to serialize and write arrays that contains plain strings. I didn't manage to get that working either.. I have a Java background so I just can't see why I couldn't just write an array to disk if it's serialized. :)

like image 710
hequ Avatar asked Apr 21 '10 18:04

hequ


1 Answers

Firstly, use the shorthand forms:

file_put_contents($filepath,serialize($var));

and

$var=unserialize(file_get_contents($filepath));

And then output/debug at each stage to find where the problem is.

like image 154
zaf Avatar answered Oct 23 '22 01:10

zaf