php序列化serialize() 与反序列化unserialize()
程序员文章站
2022-05-15 12:00:09
...
在php中,可以对数组,变量,对象等进行序列化(静态变量,常量不会被序列化)
$varname = $value; } public function __get($varname) { return $this->$varname; } } $data = array( 'name'=>'zhangsan', 'password'=>'pwd123' ); $test = 'abcd'; $ts = new TestSerialize(); $ts->name = 'zhangsan_2'; $ts->password = 'pwd123_2'; echo 'var=>'.serialize($test).'
'; echo 'array=>'.serialize($data).'
'; echo 'object=>'.serialize($ts).'
'; ?>
输出结果
var=>s:4:"abcd"; array=>a:2:{s:4:"name";s:8:"zhangsan";s:8:"password";s:6:"pwd123";} object=>O:13:"TestSerialize":2:{s:19:"TestSerializename";s:10:"zhangsan_2";s:23:"TestSerializepassword";s:8:"pwd123_2";}
序列化产生的数据可以保存在本地文件中,也可以进行网络传输
function writeObject($filename,$data='') { if(!file_exists(dirname(__FILE__).'/tmp/')) { mkdir(dirname(__FILE__).'/tmp/'); } $fp = fopen ( dirname(__FILE__).'/tmp/'.$filename, "w+" ); if (flock($fp, LOCK_EX )) //给文件加锁 { fwrite($fp, $data ); flock( $fp, LOCK_UN ); //给文件解锁 } else { echo 'Couldn\'t lock the file !'; } fclose ( $fp ); } function readObject($filename) { if(file_exists(dirname(__FILE__).'/tmp/'.$filename)) { $fp = fopen ( dirname(__FILE__).'/tmp/'.$filename, "r" ); stream_set_timeout($fp,2); $contents = fread($fp, filesize(dirname(__FILE__).'/tmp/'.$filename)); fclose ($fp); return $contents; } return NULL; }
测试一下
writeObject('data.txt',serialize($data)); writeObject('array.txt',serialize($test)); writeObject('object.txt',serialize($ts)); echo readObject('data.txt'); echo readObject('data.txt'); echo readObject('data.txt');
打印结果
a:2:{s:4:"name";s:8:"zhangsan";s:8:"password";s:6:"pwd123";}s:4:"abcd";O:13:"TestSerialize":2:{s:19:"TestSerializename";s:10:"zhangsan_2";s:23:"TestSerializepassword";s:8:"pwd123_2";}
为了保证持久化的有效性,我们可以对从数据库读取出来的文件反序列化
$f_data = readObject('data.txt'); $f_array = readObject('array.txt'); $f_object = readObject('object.txt'); $d = unserialize($f_data); $a = unserialize($f_array); $u = unserialize($f_object); print_r($d); echo '
'; echo $a; echo '
'; echo $u->name;
输出结果
Array ( [name] => zhangsan [password] => pwd123 ) abcd zhangsan_2
本文链接:
收藏随意^^请保留教程地址.
上一篇: PHP生成唯一订单号的方法汇总_PHP