Share a PHP version of JSON data formatting function _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Share a json data formatting function for PHP. Today, I saw a piece of code on the mango site, which was quite good, so I reprinted it. The following is the original text. Format JSON data in string form into indent form. I usually see a piece of code in the mango site using json today. it feels pretty good, so I reprinted it. The following is the original text.

Format JSON data in string form into indent form. Generally, the JSON string converted using json_encode is not indented. this method is much better.
Here, tab indentation is used by default. to change it to a space, replace the variable $ indentStr.

/**
* Indents a flat JSON string to make it more human-readable.
* @ Param string $ json The original JSON string to process.
* @ Return string Indented version of the original JSON string.
*/
Function indent ($ json ){

$ Result = '';
$ Pos = 0;
$ StrLen = strlen ($ json );
$ IndentStr = '';
$ NewLine = "\ n ";
$ PrevChar = '';
$ OutOfQuotes = true;

For ($ I = 0; $ I <= $ strLen; $ I ++ ){

// Grab the next character in the string.
$ Char = substr ($ json, $ I, 1 );
// Are we inside a quoted string?
If ($ char = '"' & $ prevChar! = '\\'){
$ OutOfQuotes =! $ OutOfQuotes;
// If this character is the end of an element,
// Output a new line and indent the next line.
} Else if ($ char = '}' | $ char = ']') & $ outOfQuotes ){
$ Result. = $ newLine;
$ Pos --;
For ($ j = 0; $ j <$ pos; $ j ++ ){
$ Result. = $ indentStr;
}
}
// 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 = '[') & $ outOfQuotes ){
$ Result. = $ newLine;
If ($ char = '{' | $ char = '['){
$ Pos ++;
}
For ($ j = 0; $ j <$ pos; $ j ++ ){
$ Result. = $ indentStr;
}
}
$ PrevChar = $ char;
}

Return $ result;

}

Bytes. The following is the original text. Format JSON data in string form into indent form. Json...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.