亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

漂亮-用PHP打印JSON

漂亮-用PHP打印JSON

PHP
Helenr 2019-06-19 10:33:25
漂亮-用PHP打印JSON我正在構建一個將JSON數據提供給另一個腳本的PHP腳本。我的腳本將數據構建到一個大型關聯數組中,然后使用json_encode..下面是一個示例腳本:$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');header('Content-type: text/javascript');echo json_encode($data);上面的代碼產生以下輸出:{"a":"apple","b":"banana","c":"catnip"}如果您有少量的數據,這是很好的,但是我更喜歡這樣的東西:{     "a": "apple",     "b": "banana",     "c": "catnip"}有什么方法可以在PHP中做到這一點而不受攻擊呢?好像有人在臉書弄明白了。
查看完整描述

3 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

這個函數將使用JSON字符串并縮進它的可讀性。它也應該是趨同的,

prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

輸入

{"key1":[1,2,3],"key2":"value"}

輸出量

{
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"}

電碼

function prettyPrint( $json ){
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;}


查看完整回答
反對 回復 2019-06-19
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

許多用戶建議您使用

echo json_encode($results, JSON_PRETTY_PRINT);

這是絕對正確的。但這還不夠,瀏覽器需要了解數據的類型,您可以在回顯數據回顯給用戶之前指定標頭。

header('Content-Type: application/json');

這將導致格式化良好的輸出。

或者,如果您喜歡擴展,可以在Chrome上使用JSONView。


查看完整回答
反對 回復 2019-06-19
  • 3 回答
  • 0 關注
  • 798 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號