Don't understand serialize ()

I am considering this function: serialize () for PHP, and I really don't understand what this function is. Can someone provide a simple output example?

+5
source share
3 answers

In principle, the goal serializeis to convert any (largest) data type to a string, so it can be transferred, stored, ...

Quick example:

$my_array = array(
    'a' => 10,
    'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;

You will get this result:

a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}


And, later, you can unserializethis line to return the original data:

$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);

You'll get:

array
  'a' => int 10
  'glop' => 
    array
      0 => string 'test' (length=4)
      1 => string 'blah' (length=4)


General use:

  • Ability to transfer (almost) any PHP data from one PHP script to another
  • () PHP - ,
  • - (APC, memcached, files,...),

, , serialize , PHP ( PHP , PHP- ); , - , PHP ( PHP). XML, JSON (. json_encode json_decode),...


PHP , .

+14

, , , serialize() ( unserialize()) , , .

json_encode() json_decode() , , JSON.

+2

See this example should be pretty clear.

0
source

All Articles