Pretty-Printing JSON with PHP

后端 未结 24 1876
一向
一向 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 02:57

    You could do it like below.

    $array = array(
       "a" => "apple",
       "b" => "banana",
       "c" => "catnip"
    );
    
    foreach ($array as $a_key => $a_val) {
       $json .= "\"{$a_key}\" : \"{$a_val}\",\n";
    }
    
    header('Content-Type: application/json');
    echo "{\n"  .rtrim($json, ",\n") . "\n}";
    

    Above would output kind of like Facebook.

    {
    "a" : "apple",
    "b" : "banana",
    "c" : "catnip"
    }
    

提交回复
热议问题