PHP 用于显示JSON Raw的PHP函数更具可读性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 用于显示JSON Raw的PHP函数更具可读性相关的知识,希望对你有一定的参考价值。

function json_reader($json = '', $indentStr = "     ", $newLine = "<br/>") {

        $result    = "";          // Resulting string
        $indention = "";          // Current indention after newline
        $pos       = 0;           // Indention width
        $escaped   = false;       // FALSE or escape character
        $strLen    = strlen($json);

       
        for ($i = 0; $i < $strLen; $i++) {
            // Grab the next character in the string
            $char = $json[$i];

            if ($escaped) {
                if ($escaped == $char) {
                    // End of escaped sequence
                    $escaped = false;
                }

                $result .= $char;
                if ($char == "\\" && $i + 1 < $strLen) {
                    // Next character will NOT end this sequence
                    $result .= $json[++$i];
                }

                continue;
            }

            if ($char == '"' || $char == "'") {
                // Escape this string
                $escaped = $char;
                $result .= $char;
                continue;
            }

            // If this character is the end of an element,
            // output a new line and indent the next line
            if ($char == '}' || $char == ']') {
                $indention = str_repeat($indentStr, --$pos);
                $result .= $newLine . $indention;
            }

            // Add the character to the result string
            $result .= $char;

            // If the last character was the beginning of an element,
            // output a new line and indent the next line
            if ($char == ',' || $char == '{' || $char == '[') {
                if ($char == '{' || $char == '[') {
                    $indention = str_repeat($indentStr, ++$pos);
                }
                $result .= $newLine . $indention;
            }
        }

        return  $result;
}

以上是关于PHP 用于显示JSON Raw的PHP函数更具可读性的主要内容,如果未能解决你的问题,请参考以下文章

markdown 代码复杂性报告,用于比较在PHP Raw Raw中编写`clamp`函数的各种样式

markdown 用于比较在PHP Raw中编写`clamp`函数的各种样式的代码量

php PHP的简单JSON响应函数。用于各种PhileCMS插件。

PHP md5_file() 函数用于判断文件是否有修改

PHP md5_file() 函数用于判断文件是否有修改

file_get_contents(“php:// input”)或$ HTTP_RAW_POST_DATA,哪一个更好地获取JSON请求的主体?