Skip to content

Instantly share code, notes, and snippets.

@ircmaxell
Created April 8, 2012 04:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ircmaxell/2334778 to your computer and use it in GitHub Desktop.
Save ircmaxell/2334778 to your computer and use it in GitHub Desktop.
PHP JSON dump
<?php
function dumpToJson($var, $encode = true, array $recursionCache = array()) {
$tmp = serialize($var);
if (isset($recursionCache[$tmp])) {
return 'recursion';
}
$recursionCache[$tmp] = true;
$result = array();
$result['type'] = gettype($var);
switch ($result['type']) {
case 'resource':
$result['resourceType'] = get_resource_type($var);
case 'boolean':
$result['value'] = (int) $var;
break;
case 'array':
$result['value'] = array();
foreach ($var as $key => $value) {
$result['value'][$key] = dumpToJson($value, false, $recursionCache);
}
break;
case 'object':
$r = new ReflectionObject($var);
$result['class'] = $r->getName();
$result['value'] = array();
foreach ($r->getProperties() as $prop) {
$prop->setAccessable(true);
$result['value'][$prop->getName()] = dumpToJson($prop->getValue($var), false, $recursionCache);
}
break;
case 'integer':
case 'double':
case 'string':
case 'NULL':
default:
$result['value'] = $var;
break;
}
if ($encode) {
return json_encode($result);
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment