Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize or json in PHP?

So I need to encode an array in PHP and store it in plain text in MySQL database, my question is should I use serialize() or json_encode()? What are the advantages and disadvantages of each of them?

I think either of them would do in this situation. But which one would you prefer and why? If it is for something other than an array?

like image 443
datasn.io Avatar asked Apr 04 '10 14:04

datasn.io


People also ask

What is the difference between JSON and serialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

What is serialize in PHP?

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.

Is JSON used for serialization?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.

Why do we need JSON serialization?

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.


1 Answers

Main advantage of serialize : it's specific to PHP, which means it can represent PHP types, including instances of your own classes -- and you'll get your objects back, still instances of your classes, when unserializing your data.


Main advantage of json_encode : JSON is not specific to PHP : there are libraries to read/write it in several languages -- which means it's better if you want something that can be manipulated with another language than PHP.

A JSON string is also easier to read/write/modify by hand than a serialized one.

On the other hand, as JSON is not specific to PHP, it's not aware of the stuff that's specific to PHP -- like data-types.


As a couple of sidenotes :

  • Even if there is a small difference in speed between those two, it shouldn't matter much : you will probably not serialize/unserialize a lot of data
  • Are you sure this is the best way to store data in a database ?
    • You won't be able to do much queries on serialized strins, in a DB : you will not be able to use your data in where clauses, nor update it without the intervention of PHP...
like image 88
Pascal MARTIN Avatar answered Oct 02 '22 16:10

Pascal MARTIN