Skip to content

Instantly share code, notes, and snippets.

@LeoOnTheEarth
Last active January 2, 2016 14:08
Show Gist options
  • Save LeoOnTheEarth/8314250 to your computer and use it in GitHub Desktop.
Save LeoOnTheEarth/8314250 to your computer and use it in GitHub Desktop.
Output a Human Readable JSON String
<?php
$test = array(
'foo' => array(
array('foo
bar
foobar', 'foo', 'bar'),
array('bar', 'foo', 'foobar 123'),
),
'bsr' => array(
'bar' => array(
array('abc', 'def', 'ghi'),
array('abc', 'def', 'ghi'),
array('abc', 'def', 'ghi'),
array('abc', 'def', 'ghi'),
),
'foo' => 'bar',
),
);
echo JSON::encode($test, JSON_PRETTY_PRINT);
/*
* Output:
*
* {
* "foo":
* [
* ["foo\nbar\nfoobar","foo","bar"],
* ["bar","foo","foobar 123"]
* ],
* "bsr":{
* "bar":
* [
* ["abc","def","ghi"],
* ["abc","def","ghi"],
* ["abc","def","ghi"],
* ["abc","def","ghi"]
* ],
* "foo":"bar"
* }
* }
*/
<?php
/**
* Class JSON
*/
class JSON
{
/**
* (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
* Returns the JSON representation of a value
*
* @param mixed $value <p>
* The <i>value</i> being encoded. Can be any type except
* a resource.
* </p>
* <p>
* This function only works with UTF-8 encoded data.
* </p>
* @param int $options [optional] <p>
* Bitmask consisting of <b>JSON_HEX_QUOT</b>,
* <b>JSON_HEX_TAG</b>,
* <b>JSON_HEX_AMP</b>,
* <b>JSON_HEX_APOS</b>,
* <b>JSON_NUMERIC_CHECK</b>,
* <b>JSON_PRETTY_PRINT</b>,
* <b>JSON_UNESCAPED_SLASHES</b>,
* <b>JSON_FORCE_OBJECT</b>,
* <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
* constants is described on
* the JSON constants page.
* </p>
*
* @return string A JSON encoded string on success or <b>FALSE</b> on failure.
*
* @link http://php.net/manual/en/function.json-encode.php
*/
public static function encode($value, $options = 0)
{
if ($options & JSON_PRETTY_PRINT) {
return self::prettyPrint($value, $options);
}
return json_encode($value, $options);
}
/**
* (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
* Decodes a JSON string
*
* @param string $json <p>
* The <i>json</i> string being decoded.
* </p>
* <p>
* This function only works with UTF-8 encoded data.
* </p>
* @param bool $assoc [optional] <p>
* When <b>TRUE</b>, returned objects will be converted into
* associative arrays.
* </p>
* @param int $depth [optional] <p>
* User specified recursion depth.
* </p>
* @param int $options [optional] <p>
* Bitmask of JSON decode options. Currently only
* <b>JSON_BIGINT_AS_STRING</b>
* is supported (default is to cast large integers as floats)
* </p>
*
* @return mixed the value encoded in <i>json</i> in appropriate
* PHP type. Values true, false and
* null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b>
* and <b>NULL</b> respectively. <b>NULL</b> is returned if the
* <i>json</i> cannot be decoded or if the encoded
* data is deeper than the recursion limit.
*
* @link http://php.net/manual/en/function.json-decode.php
*/
public static function decode($json, $assoc = false, $depth = 512, $options = 0)
{
return json_decode($json, $assoc, $depth, $options);
}
/**
* Output a Human Readable JSON String
*
* @param mixed $value The Variable that need to be show
* with a Human Readable JSON String.
* @param int $options [optional] <p>
* Bitmask consisting of <b>JSON_HEX_QUOT</b>,
* <b>JSON_HEX_TAG</b>,
* <b>JSON_HEX_AMP</b>,
* <b>JSON_HEX_APOS</b>,
* <b>JSON_NUMERIC_CHECK</b>,
* <b>JSON_UNESCAPED_SLASHES</b>,
* <b>JSON_FORCE_OBJECT</b>,
* <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
* constants is described on
* the JSON constants page.
* </p>
*
* @return string
*/
public static function prettyPrint($value, $options = 0)
{
// Use options, except for JSON_PRETTY_PRINT
$options = $options & ~JSON_PRETTY_PRINT;
$string = self::encode($value, $options);
$tab = ' ';
$newline = PHP_EOL;
$tabCount = 0;
$result = '';
$inQuote = false;
$inPureArray = false;
$length = strlen($string);
for ($i = 0; $i < $length; ++$i) {
$char = $string[$i];
if ($char == '"' AND $string[$i - 1] != '\\') {
$inQuote = !$inQuote;
}
if ($inQuote) {
$result .= $char;
continue;
}
switch ($char) {
case '{':
$result .= $char . $newline . str_repeat($tab, ++$tabCount);
break;
case '[':
$subString = substr($string, $i + 1);
$nextArrayTailPosition = strpos($subString, ']');
$subString = substr($subString, 0, $nextArrayTailPosition);
$nextArrayHeadPosition = strpos($subString, '[');
$nextObjectHeadPosition = strpos($subString, '{');
if (false === $nextArrayHeadPosition AND false === $nextObjectHeadPosition) {
$inPureArray = true;
}
++$tabCount;
if ($inPureArray) {
$result .= ' ' . $char;
} else {
if ($i) {
$result .= $newline;
}
$result .= str_repeat($tab, $tabCount - 1) . $char . $newline . str_repeat($tab, $tabCount);
}
break;
case '}':
$result .= $newline . str_repeat($tab, --$tabCount) . $char;
break;
case ']':
--$tabCount;
if ($inPureArray) {
$result .= $char;
} else {
$result .= (in_array($string[$i - 1], array(']', '}')) ? $newline : '') . str_repeat($tab, $tabCount) . $char;
}
$inPureArray = false;
break;
case ',':
$result .= $char;
if (isset($string[$i + 1]) AND '{' === $string[$i + 1]) {
$result .= $newline . str_repeat($tab, $tabCount);
} elseif (! $inPureArray) {
$result .= $newline . str_repeat($tab, $tabCount);
}
break;
default:
$result .= $char;
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment