Home > Backend Development > PHP Tutorial > How to serialize and deserialize data in php

How to serialize and deserialize data in php

墨辰丷
Release: 2023-03-30 09:16:01
Original
1355 people have browsed it

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, serialize and unserialize.
serialize Format the array into an ordered string
unserialize Restore the array into an array
For example:

$user=array('Moe','Larry','Curly'); 
$user=serialize($stooges); 
echo &#39;<pre class="brush:php;toolbar:false">&#39;; 
print_r($user); 
echo &#39;<br />&#39;; 
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 )
Copy after login

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 functions base64_encode and base64_decode .
For example:

$user=array(&#39;Moe&#39;,&#39;Larry&#39;,&#39;Curly&#39;); 
$user=base64_encode(serialize($user)); 
$user=unserialize(base64_decode($user));
Copy after login

This way there will be no garbled code problems, but base64 encoding increases the length of the stored string.

From the above we can summarize a own serialization 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))); 
}
Copy after login

Summary: The above is The entire content of this article is hoped to be helpful to everyone's study.

Related recommendations:

Detailed explanation of usage and examples of PHP template engine Smarty’s configuration file in template variables

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!

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