How PHP can serialize and deserialize data

Source: Internet
Author: User
This article mainly introduces how to serialize and deserialize the data of PHP, the interested friend's reference, I hope to help you.

PHP actually uses two functions,serialize and Unserialize, to serialize and deserialize data.
serialize formatting an array into an ordered string
unserialize to restore an array to a group
For example:

$user =array (' Moe ', ' Larry ', ' Curly '); $user =serialize ($stooges); Echo ' <pre> '; Print_r ($user); echo ' <br/> '; Print_r (Unserialize ($user));

Results:

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 values contain characters such as double quotes, single quotes, colons, or Chinese, they are deserialized, and the problem of garbled or scrambled formatting can occur.

To solve garbled problems, you can use base64_encode and Base64_decode two functions.
For example:

$user =array (' Moe ', ' Larry ', ' Curly '); $user =base64_encode (Serialize ($user)); $user =unserialize (Base64_decode ($user));

This will not show the problem of garbled class, but the base64 encoding increases the length of the stored string .

From the above we can summarize one of our own serialization and deserialization functions , as follows:

function my_serialize ($obj _array) {   return Base64_encode (gzcompress (Serialize ($obj _array))}//Deserialization function my _unserialize ($str) {   return unserialize (gzuncompress (Base64_decode ($STR)));}

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.