Php serialization functions serialize () and unserialize () compared with native functions, php serialization Functions

Source: Internet
Author: User

Php serialization functions serialize () and unserialize () compared with native functions, php serialization Functions

Php has a good method of formatting strings and converting them into arrays or objects, that is, serialization.
There are two methods to serialize variables.

The following example uses the serialize () and unserialize () functions:

// a complex array$myvar = array( 'hello', 42, array(1,'two'), '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:"two";}i:3;s:5:"apple";}*/// you can reproduce the original variable$newvar = unserialize($string);print_r($newvar);/* printsArray(  [0] => hello  [1] => 42  [2] => Array    (      [0] => 1      [1] => two    )  [3] => apple)*/

This is the native PHP serialization method.

However, as JSON has gained 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', 42, array(1,'two'), 'apple');// convert to a string$string = json_encode($myvar);echo $string;/* prints["hello",42,[1,"two"],"apple"]*/// you can reproduce the original variable$newvar = json_decode($string);print_r($newvar);/* printsArray(  [0] => hello  [1] => 42  [2] => Array    (      [0] => 1      [1] => two    )  [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.

The above is all the content of this article. I hope you will like it.

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.