简体   繁体   English

PHP如何序列化对象数组?

[英]php how to serialize array of objects?

I have small class called 'Call' and I need to store these calls into a flat file. 我有一个名为“ Call”的小类,我需要将这些调用存储到一个平面文件中。 I've made another class called 'CallStorage' which contains an array where I put these calls into. 我制作了另一个名为“ CallStorage”的类,其中包含一个将这些调用放入其中的数组。

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. 我试图使用serialize()和unserialize()来实现这一点,但是它们似乎有些奇怪,并且部分信息会丢失。

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. 我也没有设法使它正常工作。我有Java背景,所以我看不出为什么如果不能序列化就不能只将数组写入磁盘。 :) :)

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. 然后在每个阶段输出/调试以查找问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM