php直接輸出json格式
php直接輸出json格式,很多新手有一個誤區,以為用echo json_encode($data);這樣就是輸出json資料了,沒錯這樣輸出文本是json格式文本而不是json資料,正確的寫法是應該加一句:
| 代碼如下 |
複製代碼 |
<?php header('Content-type:text/json'); //這句是重點,它告訴接收資料的對象此頁面輸出的是json資料; $json={"name":"yovae","password":"12345"}; //雖然這行資料形式上是json格式,如果沒有上面那句的話,它是不會被當做json格式的資料被處理的; echo $json; ?> |
例子
JSON 資料格式化函數
將字串形式的 JSON 資料格式化為縮排形式。通常使用 json_encode 轉換出來的 JSON 串沒有縮排,有這個方法就爽多了。
這裡我預設使用了 tab 縮排,如果要改成空格,替換變數 $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;
} |
好了這樣輸出的的json資料庫非常漂亮格式化的形式了哦,在這裡我就不給例子了哦,大家不防進入參考一下吧。