Comparison between PHP serialization function serialize and native methods

*文
Release: 2023-03-18 17:14:01
Original
1451 people have browsed it

This article mainly introduces the comparison between the PHP serialization functions serialize() and unserialize() and the PHP native serialization method. I hope to be helpful.

There is a good way in PHP to format strings and convert them into arrays or objects, that is, serialization.
There are two ways 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;
/* prints
a: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);
/* prints
Array
(
  [0] => hello
  [1] => 42
  [2] => Array
    (
      [0] => 1
      [1] => two
    )

  [3] => apple
)
*/
Copy after login


This is the native PHP serialization method.

However, due to the popularity of JSON in recent years, support for the JSON format has been added to PHP5.2.

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);
/* prints
Array
(
  [0] => hello
  [1] => 42
  [2] => Array
    (
      [0] => 1
      [1] => two
    )

  [3] => apple
)
*/
Copy after login

This will be more effective, especially with JavaScript, etc. Many other languages ​​are compatible.

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

Related recommendations:

Introduction to serialization examples of php data

PHP Serialize serialize object method tutorial

Detailed introduction to serialization and deserialization

The above is the detailed content of Comparison between PHP serialization function serialize and native methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!