Skip to content

Instantly share code, notes, and snippets.

@karkoonzaid
Last active August 29, 2015 14:12
Show Gist options
  • Save karkoonzaid/a1f95da777ab8a42ebb9 to your computer and use it in GitHub Desktop.
Save karkoonzaid/a1f95da777ab8a42ebb9 to your computer and use it in GitHub Desktop.

Revisions

  1. @GloryFish GloryFish revised this gist Jun 24, 2011. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions pretty-json.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    <?php

    /**
    * Formats a JSON string for pretty printing
    *
  2. @GloryFish GloryFish created this gist Jun 24, 2011.
    57 changes: 57 additions & 0 deletions pretty-json.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    /**
    * Formats a JSON string for pretty printing
    *
    * @param string $json The JSON to make pretty
    * @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks
    * @return string The prettified output
    * @author Jay Roberts
    */
    function _format_json($json, $html = false) {
    $tabcount = 0;
    $result = '';
    $inquote = false;
    $ignorenext = false;

    if ($html) {
    $tab = "&nbsp;&nbsp;&nbsp;";
    $newline = "<br/>";
    } else {
    $tab = "\t";
    $newline = "\n";
    }

    for($i = 0; $i < strlen($json); $i++) {
    $char = $json[$i];

    if ($ignorenext) {
    $result .= $char;
    $ignorenext = false;
    } else {
    switch($char) {
    case '{':
    $tabcount++;
    $result .= $char . $newline . str_repeat($tab, $tabcount);
    break;
    case '}':
    $tabcount--;
    $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
    break;
    case ',':
    $result .= $char . $newline . str_repeat($tab, $tabcount);
    break;
    case '"':
    $inquote = !$inquote;
    $result .= $char;
    break;
    case '\\':
    if ($inquote) $ignorenext = true;
    $result .= $char;
    break;
    default:
    $result .= $char;
    }
    }
    }

    return $result;
    }