Created
December 30, 2013 20:19
-
-
Save goliatone/8187548 to your computer and use it in GitHub Desktop.
PHP Pretty json encode, for PHP < 5.4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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