Home >Backend Development >PHP Tutorial >Detailed explanation of serialization and deserialization operations in PHP

Detailed explanation of serialization and deserialization operations in PHP

黄舟
黄舟Original
2017-03-22 09:36:541177browse

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:

##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);
?>

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)";
?>

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!

Statement:
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