且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用php serialize()和unserialize()

更新时间:2022-06-12 08:56:21

PHP数组或对象或其他复杂数据结构不能在运行 PHP的外部传输或存储或以其他方式使用脚本.如果您想坚持这样一个复杂的数据结构,而不是单次运行脚本,则需要对其进行序列化.那只是意味着将结构放入一个较低的公分母"中,该非母分母可以由PHP以外的其他事物处理,例如数据库,文本文件,套接字.标准的PHP函数serialize只是表达这种内容的一种格式,它将数据结构序列化为PHP独有的字符串表示形式,并且可以使用unserialize反向转换为PHP对象.但是,还有许多其他格式,例如JSON或XML.

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.

以这个常见问题为例:

PHP和Javascript只能通过字符串进行通信.您可以很容易地将字符串"foo"传递给Javascript.您可以很容易地将数字1传递给Javascript.您可以轻松地将布尔值truefalse传递给Javascript.但是如何将这个数组传递给Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

答案是序列化.对于PHP/Javascript,JSON实际上是更好的序列化格式:

The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

JavaScript可以轻松地将其转换为实际的Javascript数组.

Javascript can easily reverse this into an actual Javascript array.

这与相同数据结构的表示同样有效:

This is just as valid a representation of the same data structure though:

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

但是几乎只有PHP使用它,其他任何地方对此格式几乎没有支持.
这是很常见的,也得到了很好的支持:

But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:

<array>
    <element key='1'>elem 1</element>
    <element key='2'>elem 2</element>
    <element key='3'>elem 3</element>
</array>

在许多情况下,您需要将复杂的数据结构作为字符串传递.序列化将任意数据结构表示为字符串,解决了该问题.

There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.