This paper mainly introduces the PHP serialization function serialize () and unserialize () compared to the native serialization method of PHP. We hope to help you.
PHP has a good way to format strings and convert an array or object, that is, serialization processing.
There are two ways to serialize variables.
The following example uses the Serialize () and Unserialize () functions:
A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' Apple ');/convert to a string$string = serialize ($myvar); echo $string;/* printsa:4:{i:0;s:5: "Hello"; I:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: "Both";} I:3;s:5: "Apple";} *///You can reproduce the original Variable$newvar = Unserialize ($string);p rint_r ($newvar);/* Printsarray ( [0] = > Hello [1] = [ 2] = = Array ( [0] = 1 [1] +- ) [3] = apple) */
This is the native PHP serialization method.
However, thanks to JSON's popularity in recent years, PHP5.2 has added support for JSON format.
Now you can use the Json_encode () and Json_decode () functions:
A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' Apple ');/convert to a string$string = Json_encode ($myvar echo $string;/* prints["Hello", 42,[1, "I", "Apple"]*///you can reproduce the original Variable$newvar = Json_decode ( $string);p Rint_r ($newvar);/* Printsarray ( [0] = = Hello [1] = [2] = = Array ( [0] = = 1 [1] = ( ) [3] = apple) */
This will be more effective, especially compatible with many other languages such as JavaScript.
Note: For complex objects, some information may be lost.
Related recommendations:
Introduction to a serialized instance of PHP data
Tutorials for PHP serialization of Serialize objects
A detailed description of serialization and deserialization