php serialize object to json

Solutions on MaxInterview for php serialize object to json by the best coders in the world

showing results for - "php serialize object to json"
Fabio
31 Apr 2017
1edit: it's currently 2016-09-24, and PHP 5.4 has been released 2012-03-01, and support has ended 2015-09-01. Still, this answer seems to gain upvotes. If you're still using PHP < 5.4, your are creating a security risk and endagering your project. If you have no compelling reasons to stay at <5.4, or even already use version >= 5.4, do not use this answer, and just use PHP>= 5.4 (or, you know, a recent one) and implement the JsonSerializable interface
2
3You would define a function, for instance named getJsonData();, which would return either an array, stdClass object, or some other object with visible parameters rather then private/protected ones, and do a json_encode($data->getJsonData());. In essence, implement the function from 5.4, but call it by hand.
4
5Something like this would work, as get_object_vars() is called from inside the class, having access to private/protected variables:
6
7function getJsonData(){
8    $var = get_object_vars($this);
9    foreach ($var as &$value) {
10        if (is_object($value) && method_exists($value,'getJsonData')) {
11            $value = $value->getJsonData();
12        }
13    }
14    return $var;
15}