Serialize/unserialize PHP object-graph to JSON Serialize/unserialize PHP object-graph to JSON json json

Serialize/unserialize PHP object-graph to JSON


The finished script (posted above) meets my precise requirements:

  • Serialize and unserialize an entire aggregate.

  • Have a JSON representation that closely resembles the original data-structure.

  • Do not pollute the data-structure with dynamically generated keys or other data.

It does not handle circular references. As pointed out in a comment above there is no right way to store circular references or multiple references to the same object, as these are all equal. Realizing this, I decided my object-graph must be a regular tree, and accepted this limitation as "a good thing".

update: the ouput can now be formatted with indentation, newlines and whitespace - it was important for me to have a human-readable (and source-control friendly) representation for my purposes. (The formatting can be enabled or disabled as needed.)


I don't know if this is what you are after, but if you are only interested in getting at public properties of a object, get_object_vars($obj) will do the trick.

<?phpclass foo {    public $fname = "John";    public $sname = "Doe";    private $status = null;    static $type = "person";}$obj = new foo;print_r( (get_object_vars($obj)) );print json_encode(get_object_vars($obj));?>

Will output :

Array ( [fname] => John [sname] => Doe )

{"fname":"John","sname":"Doe"}

The above method is useless for accessing function references and private variables but you might be able to use this in conjunction with some more code to knock up what you want.

Dinesh.