Serialization in PHP

Source: Internet
Author: User
PHP Serialization functions are often used. when you need to store data in a database or file, you can use serialize () and unserialize () in PHP () method to implement serialization and deserialization. the code is as follows:

PHP Serialization functions are often used. when you need to store data in a database or file, you can use serialize () and unserialize () in PHP () method to achieve serialization and deserialization, the code is as follows:

Php code

  1. // A complex array
  2. $ Myvar = array (
  3. 'Hello ',
  4. 42,
  5. Array (1, 'two '),
  6. 'Apple'
  7. );
  8. // Serialization
  9. $ String = serialize ($ myvar );
  10. Echo $ string;
  11. /* Output
  12. 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 ";}
  13. */
  14. // Reverse sample
  15. $ Newvar = unserialize ($ string );
  16. Print_r ($ newvar );
  17. /* Output
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */

How to serialize data to json format? rest assured that php is ready for you. users who use php 5.2 or later can use the json_encode () and json_decode () functions to serialize data in json format, the code is as follows:

Php code
// 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
)
*/

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.