Detailed explanation of serialization and deserialization operations in PHP

黄舟
Release: 2023-03-06 20:10:02
Original
1153 people have browsed it

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);
Copy after login

Specific example:

##1. Perform serialization operation in xxx1.php

<?php
$v1 = 1;
$v2 = &#39;abc&#39;;
$v3 = array(&#39;a&#39;=>1,&#39;bb&#39;=>2.2,&#39;awd&#39;,true);
$str1 = serialize($v1);
$str2 = serialize($v2);
$str3 = serialize($v3);

//写入文本文件
file_put_contents(&#39;./a1.txt&#39;, $str1);
file_put_contents(&#39;./a2.txt&#39;, $str2);
file_put_contents(&#39;./a3.txt&#39;, $str3);
?>
Copy after login

2. Deserialize in xxx2.php

<?php
$s1 = file_get_contents(&#39;./a1.txt&#39;);
$s2 = file_get_contents(&#39;./a2.txt&#39;);
$s3 = file_get_contents(&#39;./a3.txt&#39;);
$var1 = unserialize($s1);
$var2 = unserialize($s2);
$var3 = unserialize($s3);
echo "<br/>var_dump($var1,$var2,$var3)";
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template