Pretty-Printing JSON with PHP

后端 未结 24 1839
一向
一向 2020-11-22 02:03

I\'m building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode

24条回答
  •  粉色の甜心
    2020-11-22 03:02

    I realize this question is asking about how to encode an associative array to a pretty-formatted JSON string, so this doesn't directly answer the question, but if you have a string that is already in JSON format, you can make it pretty simply by decoding and re-encoding it (requires PHP >= 5.4):

    $json = json_encode(json_decode($json), JSON_PRETTY_PRINT);
    

    Example:

    header('Content-Type: application/json');
    $json_ugly = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    $json_pretty = json_encode(json_decode($json_ugly), JSON_PRETTY_PRINT);
    echo $json_pretty;
    

    This outputs:

    {
        "a": 1,
        "b": 2,
        "c": 3,
        "d": 4,
        "e": 5
    }
    

提交回复
热议问题