views:

225

answers:

3

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?

+8  A: 

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...
Pascal MARTIN
+3  A: 

Well firstly serializing an array or object and storing it in a database is typically a code smell. Sometimes people end up putting a comma separated list into a column and then get into all sorts of trouble when they later find out they need to query on it.

So think very carefully about that if this is that kind of situation.

As for the differences. PHP serialize is probably more compact but only usable with PHP. JSON is cross-platform and possibly slower to encode and decode (although I doubt meaningfully so).

cletus
+1  A: 

If you data will never has to leave your PHP application, I recommend serialize() because it offers a lot of extra functionality like __sleep() and __wakeup() methods for your objects. It also restores objects as instances of the correct classes.

If you will pass the serialized data to another application, you should use JSON or XML for compatibility.

But storing a serialized objet into a database? Maybe you should think about that again. It can be real trouble later.

Techpriester