In my little age with WordPress, I’ve seen WordPress itself and its friendly plugins are using PHP serialize()
in storing data into db in many cases. But in a recent search I found a serious community support for the json_encode()
over the serialize()
.
- A test that proves
json_encode()
is better thanserialize()
– StackOverflow - Reasons why
json_encode()
can be used and why not – StackOverflow
And I personally tested an associative array with both of ’em, that shows:
-
serialize()
stores 342 chars -
json_encode()
stores 285 chars
Why I’m asking this?
I’m on a project while I’m going to store repeating meta fields to a post. Where:
- Data would be basically in English, but sometimes can be Bengali
- Data would be associative array, 3 level deep (I hope I understood levels correctly):
array(
1 => array(
'key'=>'value',
'key2'=>'value'
),
2 => array(
'key'=>'value',
'key2'=>'value'
)
)
I’ve checked the postmeta
table’s meta_value
field it’s a longtext
, that means a length of 4,294,967,295 chars (4GB).
So I need a robust solution into storing things.
I think, not 100% sure that this was the real reason the WP developers took this approach, but common sense tells me that serialize preserves the variable types and have a mini built in error detection, and json stores only string values { key : value }
, so when you go back to PHP you will have to guess the format, or make a parser for it. This will force you to have two different ways to handle your data: previous, to storing the data as json and after decoding the json it will come back as a totally different object.
This is the main reason the difference in size, PHP is storing not only an array; it is storing how many elements were in the array when it was serialized, their types, and their values.
You are not storing only key value pairs on the database but you may also be storing an object with different variable types.