note 106527 deleted from function.json-encode by danbrown
| From: | danbrown@php.net | Date: | Wed, 16 Nov 2011 16:40:08 +0000 |
| Subject: | note 106527 deleted from function.json-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-184526@lists.php.net to get a copy of this message | ||
Note Submitter: gcrico at free dot fr
----
/**
* JSON_PRETTY_PRINT for php 5.3
*
* Main useful code from https://github.com/zendframework/zf2/blob/master/library/Zend/Json/Json.php
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New
BSD License
*
* @param mixed $value
* @param integer $options
* @return string
*/
function json_encode_pretty_print($value, $options=0) {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($value, $options | JSON_PRETTY_PRINT);
}
$json = json_encode($value, $options);
//$tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
$tokens = preg_split('#(\{\}|\[\]|\{|\}|\[|\]|,|:)#', $json, -1,
PREG_SPLIT_DELIM_CAPTURE);
//echo '$tokens: '.print_r($tokens, true)."\n";
$result = "";
$indent = 0;
$ind = "\t";
$inLiteral = false;
$previous = '';
foreach($tokens as $token) {
if($token == "") continue;
$prefix = str_repeat($ind, $indent);
if(!$inLiteral && ($token == "{" || $token == "[")) {
$indent++;
if($result != "" && $result[strlen($result)-1] == "\n") {
$result .= $prefix;
}
$result .= "$token\n";
} elseif(!$inLiteral && ($token == "}" || $token == "]")) {
$indent--;
$prefix = str_repeat($ind, $indent);
$result .= "\n$prefix$token";
} elseif(!$inLiteral && $token == ",") {
$result .= "$token\n";
} elseif(!$inLiteral && ($token == "{}" || $token == "[]")) {
$result .= "$token";
} elseif(!$inLiteral && $token == ":") {
$result .= "$token ";
} else {
$result .= (($inLiteral || $previous == ':') ? '' : $prefix) . $token;
// Count # of unescaped double-quotes in token, subtract # of
// escaped double-quotes and if the result is odd then we are
// inside a string literal
if ((substr_count($token, "\"")-substr_count($token, "\\\"")) % 2
!= 0) {
$inLiteral = !$inLiteral;
}
}
$previous = $token;
}
return $result;
}