How to serialize and deserialize data in php

墨辰丷
Release: 2023-03-30 09:16:01
Original
1243 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,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 )
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 functionsbase64_encodeandbase64_decode.
For example:

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

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))); }
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!