As you know json_encode is encoding only array or public properties of an object. But print_r can expose the protected and private properties in an object. Sometimes we need to these hidden properties. For this purpose we can convert print_r result to JSON result. Here is the function we need:
if (!function_exists('pr2json')) { /** * Convert print_r result to json string. * @note Exceptions are always there i tried myself best to get it done. Here $array can be array of arrays or arrays of objects or both * @param string $string Result of `print_r($array, true)` * @return string Json string (transformed version of print_r result) */ function pr2json($string) { // replacing `stdClass Objects (` to `{` $string = preg_replace("/stdClass Object\s*\(/s", '{ ', $string); // replacing `Array (` to `{` $string = preg_replace("/Array\s*\(/s", '{ ', $string); // replacing `)\n` to `},\n` @note This might append , at the last of string as well which we will trim later on. $string = preg_replace("/\)\n/", "},\n", $string); // replacing `)` to `}` at the last of string $string = preg_replace("/\)$/", '}', $string); // replacing `[ somevalue ]` to "somevalue" $string = preg_replace("/\[\s*([^\s\]]+)\s*\](?=\s*\=>)/", '"\1" ', $string); // replacing `=> {` to `: {` $string = preg_replace("/=>\s*{/", ': {', $string); // replacing empty last values of array special case `=> \n }` to : "" \n $string = preg_replace("/=>\s*[\n\s]*\}/s", ":\"\"\n}", $string); // replacing `=> somevalue` to `: "somevalue",` $string = preg_replace("/=>\s*([^\n\"]*)/", ':"\1",', $string); // replacing last mistakes `, }` to `}` $string = preg_replace("/,\s*}/s", '}', $string); // replacing `} ,` at the end to `}` return $string = preg_replace("/}\s*,$/s", '}', $string); } }
This is generating well formed JSON string. We can convert this to a json object and then access the private/protected properties of an object.
$jsonObj = json_decode( pr2json( $privateObj ) );
Pros and Cons
print_r is dumping all data. Sometimes data can be bigger then you though and this causes a memory error. When you try to convert a big class to json string then you can face some memory issues. And the other hand normally you don’t need to private/protected properties in an object. There must be a way for accessing to private property or you don’t need it really. Actually if you try to access a private/protected property then may be you’re acting out of engineering methods.
Happy coding…
0 yorum