Skip to content

Instantly share code, notes, and snippets.

@goliatone
Created December 30, 2013 20:19
Show Gist options
  • Save goliatone/8187548 to your computer and use it in GitHub Desktop.
Save goliatone/8187548 to your computer and use it in GitHub Desktop.
PHP Pretty json encode, for PHP < 5.4
<?php
function json_readable_encode($in, $indent = 0, Closure $_escape = null)
{
if (__CLASS__ && isset($this))
{
$_myself = array($this, __FUNCTION__);
}
elseif (__CLASS__)
{
$_myself = array('self', __FUNCTION__);
}
else
{
$_myself = __FUNCTION__;
}
if (is_null($_escape))
{
$_escape = function ($str)
{
return str_replace(
array('\\', '"', "\n", "\r", "\b", "\f", "\t", '/', '\\\\u'),
array('\\\\', '\\"', "\\n", "\\r", "\\b", "\\f", "\\t", '\\/', '\\u'),
$str);
};
}
$out = '';
foreach ($in as $key=>$value)
{
$out .= str_repeat("\t", $indent + 1);
$out .= "\"".$_escape((string)$key)."\": ";
if (is_object($value) || is_array($value))
{
$out .= "\n";
$out .= call_user_func($_myself, $value, $indent + 1, $_escape);
}
elseif (is_bool($value))
{
$out .= $value ? 'true' : 'false';
}
elseif (is_null($value))
{
$out .= 'null';
}
elseif (is_string($value))
{
$out .= "\"" . $_escape($value) ."\"";
}
else
{
$out .= $value;
}
$out .= ",\n";
}
if (!empty($out))
{
$out = substr($out, 0, -2);
}
$out = str_repeat("\t", $indent) . "{\n" . $out;
$out .= "\n" . str_repeat("\t", $indent) . "}";
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment