Pretty-Printing JSON with PHP

后端 未结 24 2238
一向
一向 2020-11-22 02:03

I\'m building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode

24条回答
  •  半阙折子戏
    2020-11-22 03:07

    1 - json_encode($rows,JSON_PRETTY_PRINT); returns prettified data with newline characters. This is helpful for command line input, but as you've discovered doesn't look as pretty within the browser. The browser will accept the newlines as the source (and thus, viewing the page source will indeed show the pretty JSON), but they aren't used to format the output in browsers. Browsers require HTML.

    2 - use this fuction github

    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 = "    ";
                $newline = "
    "; } 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 '[': case '{': $tabcount++; $result .= $char . $newline . str_repeat($tab, $tabcount); break; case ']': 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; }

提交回复
热议问题