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

How to serialize and deserialize data in php

墨辰丷
墨辰丷Original
2018-06-06 15:51:351299browse

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

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 )

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

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))); 
}

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!

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