PHP serialization function Serialize vs. native methods

Source: Internet
Author: User
This paper mainly introduces the PHP serialization function serialize () and unserialize () compared to the native serialization method of PHP. We hope to help you.

PHP has a good way to format strings and convert an array or object, that is, serialization processing.
There are two ways to serialize variables.

The following example uses the Serialize () and Unserialize () functions:

A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' Apple ');/convert to a string$string = serialize ($myvar); echo $string;/* printsa:4:{i:0;s:5: "Hello"; I:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: "Both";} I:3;s:5: "Apple";} *///You can reproduce the original Variable$newvar = Unserialize ($string);p rint_r ($newvar);/* Printsarray (  [0] = > Hello  [1] = [  2] = = Array    (      [0] = 1      [1] +-    )  [3] = apple) */


This is the native PHP serialization method.

However, thanks to JSON's popularity in recent years, PHP5.2 has added support for JSON format.

Now you can use the Json_encode () and Json_decode () functions:


A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' Apple ');/convert to a string$string = Json_encode ($myvar echo $string;/* prints["Hello", 42,[1, "I", "Apple"]*///you can reproduce the original Variable$newvar = Json_decode ( $string);p Rint_r ($newvar);/* Printsarray (  [0] = = Hello  [1] =  [2] = = Array    (      [0] = = 1      [1] = (    )  [3] = apple) */

This will be more effective, especially compatible with many other languages such as JavaScript.

Note: For complex objects, some information may be lost.

Related recommendations:

Introduction to a serialized instance of PHP data

Tutorials for PHP serialization of Serialize objects

A detailed description of serialization and deserialization

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.