php how to serialize array of objects?

Posted by hequ on Stack Overflow See other posts from Stack Overflow or by hequ
Published on 2010-04-21T18:41:57Z Indexed on 2010/04/21 18:43 UTC
Read the original article Hit count: 231

Hello,

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. :)

© Stack Overflow or respective owner

Related posts about php

Related posts about serialization