Monday, March 11, 2013

json_encode vs serialize

json_encode and serialize are both PHP functions for generating a storable representation of a value. So. What do they do, and why would you choose one over the other?

What do they do?

Well, in simple terms, they flatten the data object you pass to them into a single thread or stream of data, but in such a way so that the structure of the data can be completely recovered.

Why would you do this?

To quote the php manual:
This is useful for storing or passing PHP values around without losing their type and structure.
A serialized or json'ed object becomes a single simple reference that can be bandied about willy nilly. Stored. Retrieved. Thrown down a digital pipe somewhere without regard for it's welfare. But mostly, to store it in a DB or text file

Which would I choose?

I would choose json_encode for data that I knew to be strings only (no binary data)
I would choose serialize for creating BLOBs to go into a database.
I would choose json_encode when I wanted a human readable result.
I would choose serialize for more stand-alone type objects such as a php session or php user construct.
But I'm still learning, so I might change my mind about that later :)

Example Code

<?php

// example serialize and json_encode

$var['name'] = 'John';
$var['thresh'] = 88.2;

$json = json_encode($var);
$serialized = serialize($var);

print "JSON: $json\n";
print "Serialized: $serialized\n"; // safe because we know there's no binary data

$fromJson = json_decode($json);
$fromSerialize = unserialize($serialized);

print "From JSON:\n";
print_r($fromJson);
print "From serialize:\n";
print_r($fromSerialize);

?>

Example Output




JSON: {"name":"John","thresh":88.2}
Serialized: a:2:{s:4:"name";s:4:"John";s:6:"thresh";d:88.200000000000003;}
From JSON:
stdClass Object
(
    [name] => John
    [thresh] => 88.2
)
From serialize:
Array
(
    [name] => John
    [thresh] => 88.2
)

No comments:

Post a Comment