Php directly outputs json format
Php directly outputs the json format. Many new users have a misunderstanding that echo json_encode ($ data) is used to output json data. If yes, the output text is in json format rather than json data, the correct statement should be followed by one sentence:
| The code is as follows: |
Copy code |
<? Php
Header ('content-type: text/json'); // indicates the object receiving data. json data is output on this page;
$ Json = {"name": "yovae", "password": "12345"}; // Although this line of data is in json format, if there is no such sentence, it will not be processed as json data;
Echo $ json;
?> |
Example
JSON data formatting function
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.
| The code is as follows: |
Copy code |
/**
* 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;
} |
Well, the json database output in this way is very beautiful and formatted. Here I will not give an example. Please refer to it without your defense.