This article mainly introduces how to serialize and deserialize data in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
php actually uses two functions to serialize and deserialize data,serializeandunserialize.
serializeFormat the array into an ordered string
unserializeRestore the array into an array
For example:
$user=array('Moe','Larry','Curly'); $user=serialize($stooges); echo ''; print_r($user); echo '
'; print_r(unserialize($user));Copy after login
Result:
a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";} Array ( [0] => Moe [1] => Larry [2] => Curly )
Note that when the array value contains characters such as double quotes, single quotes, colons or Chinese characters, they may be deserialized after being deserialized. There will be problems with garbled characters or disrupted formatting.
To solve the problem of garbled characters, you can use the two functionsbase64_encodeandbase64_decode.
For example:
$user=array('Moe','Larry','Curly'); $user=base64_encode(serialize($user)); $user=unserialize(base64_decode($user));
This way there will be no garbled code problems, butbase64 encoding increases the length of the stored string.
From the above we can summarize a ownserialization and deserialization function, as follows:
function my_serialize($obj_array){ return base64_encode(gzcompress(serialize($obj_array))); } //反序列化 function my_unserialize($str){ return unserialize(gzuncompress(base64_decode($str))); }
Summary: The above is The entire content of this article is hoped to be helpful to everyone's study.
Related recommendations:
About PHP reading Solution to Chinese garbled characters in mssql json data
Usage and example analysis of reserved variables in PHP template engine Smarty
The above is the detailed content of How to serialize and deserialize data in php. For more information, please follow other related articles on the PHP Chinese website!