Skip to content

Instantly share code, notes, and snippets.

@ximik777
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ximik777/22f105b1e91036131755 to your computer and use it in GitHub Desktop.
Save ximik777/22f105b1e91036131755 to your computer and use it in GitHub Desktop.
<?php
// Ab PHP 5.4 steht für json_encode die Konstante JSON_PRETTY_PRINT zur Verfügung.
echo json_encode($arr, JSON_PRETTY_PRINT);
// Für PHP <= 5.3 gibt es folgende Alternative (Quelle Zend):
/**
* Pretty-print JSON string
*
* Use 'format' option to select output format - currently html and txt supported, txt is default
* Use 'indent' option to override the indentation string set in the format - by default for the 'txt' format it's a tab
*
* @param string $json Original JSON string
* @param array $options Encoding options
* @return string
*/
function json_pretty($json, $options = array())
{
$tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
$result = '';
$indent = 0;
$format = 'txt';
//$ind = "\t";
$ind = " ";
if (isset($options['format'])) {
$format = $options['format'];
}
switch ($format) {
case 'html':
$lineBreak = '<br />';
$ind = '&nbsp;&nbsp;&nbsp;&nbsp;';
break;
default:
case 'txt':
$lineBreak = "\n";
//$ind = "\t";
$ind = " ";
break;
}
// override the defined indent setting with the supplied option
if (isset($options['indent'])) {
$ind = $options['indent'];
}
$inLiteral = false;
foreach ($tokens as $token) {
if ($token == '') {
continue;
}
$prefix = str_repeat($ind, $indent);
if (!$inLiteral && ($token == '{' || $token == '[')) {
$indent++;
if (($result != '') && ($result[(strlen($result) - 1)] == $lineBreak)) {
$result .= $prefix;
}
$result .= $token . $lineBreak;
} elseif (!$inLiteral && ($token == '}' || $token == ']')) {
$indent--;
$prefix = str_repeat($ind, $indent);
$result .= $lineBreak . $prefix . $token;
} elseif (!$inLiteral && $token == ',') {
$result .= $token . $lineBreak;
} else {
$result .= ( $inLiteral ? '' : $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;
}
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment