Skip to content

Instantly share code, notes, and snippets.

@darklow
Created April 18, 2012 13:53
Show Gist options
  • Save darklow/2413724 to your computer and use it in GitHub Desktop.
Save darklow/2413724 to your computer and use it in GitHub Desktop.
JSON Encode pretty
<?php
function json_encode_pretty($obj, $indentation = 0)
{
switch (gettype($obj))
{
case 'object':
$obj = get_object_vars($obj);
case 'array':
if (!isset($obj[0]))
{
$arr_out = array();
foreach ($obj as $key => $val)
{
$arr_out[] = '<span style="color:#333">'.addslashes($key).':</span> '.json_encode_pretty($val, $indentation + 1);
}
if (count($arr_out) < 2)
{
return '{'.implode(',', $arr_out).'}';
}
return "{\n".str_repeat(" ", $indentation + 1).implode(",\n".str_repeat(" ", $indentation + 1), $arr_out)."\n".str_repeat(" ", $indentation)."}";
}
else
{
$arr_out = array();
$ct = count($obj);
for ($j = 0; $j < $ct; $j++)
{
$arr_out[] = json_encode_pretty($obj[$j], $indentation + 1);
}
if (count($arr_out) < 2)
{
return '['.implode(',', $arr_out).']';
}
return "[\n".str_repeat(" ", $indentation + 1).implode(",\n".str_repeat(" ", $indentation + 1), $arr_out)."\n".str_repeat(" ", $indentation)."]";
}
break;
case 'NULL':
return '<span style="color:#c9f;">null</span>';
break;
case 'boolean':
return '<span style="color:#c80;">'.($obj ? 'true' : 'false').'</span>';
break;
case 'integer':
case 'double':
return '<span style="color:#47c; span-weight:bold;">'.$obj.'</span>';
break;
case 'string':
default:
$obj = str_replace(array('\\', '"',), array('\\\\', '\"'), $obj);
if(is_numeric($obj))
return '<span style="color:#47c;">"'.$obj.'"</span>';
else
return '<span style="color:green;">"'.$obj.'"</span>';
break;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment