Pretty-Printing JSON with PHP

后端 未结 24 1879
一向
一向 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:59

    The following is what worked for me:

    Contents of test.php:

    
    
    Testing JSON array output
      
      'apple', 'b'=>'banana', 'c'=>'catnip');
      // encode in json format 
      $data = json_encode($data);
    
      // json as single line
      echo "
    Json as single line
    "; echo $data; // json as an array, formatted nicely echo "
    Json as multiline array
    "; print_r(json_decode($data, true)); ?>

    output:

    Testing JSON array output
    
    
    Json as single line 
    {"a":"apple","b":"banana","c":"catnip"}
    Json as multiline array 
    Array
    (
        [a] => apple
        [b] => banana
        [c] => catnip
    )
    

    Also note the use of "pre" tag in html.

    Hope that helps someone

提交回复
热议问题