Home >Backend Development >PHP Tutorial >Detailed explanation of serialization and deserialization operations in PHP
This article mainly introduces the serialization and deserialization operations in PHP. You can convert the data of a variable into "string, with the purpose of converting the character The string is stored locally. The opposite behavior is called deserialization.
Data (variable) serialization (persistence)
Convert the data of a variable to a string, but it is not type conversion, the purpose is to store the string locally. The opposite behavior is called deserialization.
Process:
//序列化 $str = serialize($r1); //保存到本地 file_put_contents("文本文件路径",$str); //从本地取出 $str2 = file_get_contents("文本文件路径"); //反序列化为之前的对象 $v1 = unserialize($str2);
Specific example:
<?php $v1 = 1; $v2 = 'abc'; $v3 = array('a'=>1,'bb'=>2.2,'awd',true); $str1 = serialize($v1); $str2 = serialize($v2); $str3 = serialize($v3); //写入文本文件 file_put_contents('./a1.txt', $str1); file_put_contents('./a2.txt', $str2); file_put_contents('./a3.txt', $str3); ?>2. Deserialize in xxx2.php
<?php $s1 = file_get_contents('./a1.txt'); $s2 = file_get_contents('./a2.txt'); $s3 = file_get_contents('./a3.txt'); $var1 = unserialize($s1); $var2 = unserialize($s2); $var3 = unserialize($s3); echo "<br/>var_dump($var1,$var2,$var3)"; ?>
The above is the detailed content of Detailed explanation of serialization and deserialization operations in PHP. For more information, please follow other related articles on the PHP Chinese website!