PHP Serialization and deserialization

Source: Internet
Author: User

Serialization and deserialization

Compress complex data types into a string

Serialize () encodes variables and their values into textual form
Unserialize () restore the original variable

1. Create a $arr array to store the user's basic information and output the view results in the browser;

?
1234567 $arr=array();$arr[‘name‘]=‘张三‘;$arr[‘age‘]=‘22‘;$arr[‘sex‘]=‘男‘;$arr[‘phone‘]=‘123456789‘;$arr[‘address‘]=‘上海市浦东新区‘;var_dump($arr);

Output Result:

?
1234567 array (5) { [ "name" ]=> string (6) "Zhang San" [ Code class= "PHP string" > "age" ]=> string (2) "22" [ "sex" ]=> String (3) "male" [ " Phone " ]=> string (9) " 123456789 " [ "address" ]=> string (21) "Shanghai Pudong New Area"   }

2. Serialize the $arr array to the $info string and output the view results in the browser;

?
12 $info=serialize($arr);var_dump($info);

Output Result:

?
1 string "A:5:{s:4:" name Zhang San age 22 sex male phone 123456789 address ";}"

Use the serialization serialize ($arr) function to concatenate the keys and values of the elements in the array into strings in a regular order. The A:5 flag is serialized as an array that contains 5 key-value pairs, and the S:4 flag content is a string containing 4 characters.

By serializing we can store some of the modular data in the form of a string, such as a database or session, can reduce the creation of a lot of tedious data table fields, of course, serialization to string storage will add additional space, should be reasonable design and application.

3. Finally use Unserialize ($info) deserialization to restore the string to the array pattern we need;

?
12 $zhangsan=unserialize($info);var_dump($zhangsan);

Output Result:

?
1234567 array (5) { [ " name " ]=> string (6) "Zhang San" [ "age" ]=> string (2) "$" [ "sex" ]=> string (3) "male" [ "phone" ]=> string (9) "123456789" [ ]=> string (+) Code class= "PHP string" > "Shanghai Pudong New Area" }

Serialization and deserialization of PHP

Related Article

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.