Reputation: 120
Just came across serialize() in php. Many databases store the data in serialized form so curious to know what is more usefun json or serialize and why?
Json Data->["Math","Language","Science","History"]
serialized Data->a:4:{i:0;s:4:"Math";i:1;s:8:"Language";i:2;s:7:"Science";i:3;s:7:"History";}
Upvotes: 2
Views: 5506
Reputation: 4547
to complete Oleg's answer I would like to suggest you to visit this link with objetive comparisons between json_encode and serialize PHP methods:
http://www.shozab.com/php-serialization-vs-json-encoding-for-an-array
It shows how serialize is usually slower but not recommended for all situations.
And finally here you have another discussion with many contributions in stackoverflow:
Hope it will be interesting for you.
Upvotes: 1
Reputation: 2348
Serialize() is a native PHP method of storing data in text strings. It can even store objects. And it has a special notation for objects. JSON, it its turn, is a JavaScript's Object Notation. Basically, same thing. But they are used in different domains.
JSON is usually used for online communication - sending data to/from AJAX scripts, numerous API's, etc. It appeared to be much lighter and readable than XML, thus it competes with it for the most commonly used data transfer standard for APIs. It is also widely used in config files, say, for Composter - where readability is one of the top requirements. Visual readability and easy structure makes JSON the best way to communicate between different platforms and programming languages. This, last phrase is important.
PHP Serializing is used in cases where you save data in PHP and you restore data back in PHP as well. Say, you can save arrays, or $user object into a PHP session, and then restore them back. Or store a multi-dimensional array in a MySQL field, and then restore it exactly as it was in an $array variable. In most cases Serialized data is not much shorter/lighter than JSON and doesn't usually take less space - it makes it lose readability though. But there are quite powerful tricks with it PHP has - it preserves data types, classes names, visibility options, etc. Also refer to __sleep()
and __wakeup()
magic class methods allowing you to save objects on the fly and create special constructors to revive them back, again, on the fly.
In your particular case, if you store data in MySQL database with PHP, and then read it back to PHP - then PHP serialization would be the best way to use. Unless you want to access this data with other languages, or edit manually/visually.
Upvotes: 4