PHP格式化輸出json資料例子整理

來源:互聯網
上載者:User

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資料庫非常漂亮格式化的形式了哦,在這裡我就不給例子了哦,大家不防進入參考一下吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.