I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?
Definition and Usage The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.
It is not secure In addition, XML serialization works by creating temporary files. If you think you're creating temporary representations of your data (for example, to create a string that you're going to post to a web service), then files on disk will pose a potential security risk.
Definition and Usage. The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
The purpose of serializing it into JSON is so that the message will be a format that can be understood and from there, deserialize it into an object type that makes sense for the consumer.
Basically, the goal of serialize
is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
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 unserialize
that string, to get the original data back :
$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);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Note, though, that using serialize
is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode
and json_decode
), ...
In the PHP manual, you can also read the Object Serialization section, btw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With