Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format echo json_encode [duplicate]

Tags:

json

php

I would like to format the echo json_encode, the output is currently

{"results":{"course":"CC140","books":{"book":[[{"id":"300862","title":"Building object-oriented software","isbn":"0070431965","borrowedcount":"6"}]]}}}

Whereas i would like to to output like this:

{
    "results": {
        "course": "CC140",
        "books": {
            "book": [
                [
                    {
                        "id": "300862",
                        "title": "Building object-oriented software",
                        "isbn": "0070431965",
                        "borrowedcount": "6"
                    }
                ]
            ]
        }
    }
}

This is the code that makes the JSON

$temp = array();
    foreach ($my_array as $counter => $bc) {
        $temp['id'] = "$id[$counter]";
        $temp['title'] = "$title[$counter]";
        $temp['isbn'] = "$isbn[$counter]";
        $temp['borrowedcount'] = "$borrowedcount[$counter]";
        $t2[] = $temp;
    }

        $data = array(
  "results" => array(
    "course" => "$cc",
    "books" => array(
      "book" =>
      array(  
        $t2
      )
    )
  )
);
    echo json_encode($data);

Any help or pointers would be appreciated, thanks

Adding this

header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);

formats the JSON, but the header also outs the entire HTML document

like image 861
Craig Weston Avatar asked Nov 29 '22 16:11

Craig Weston


2 Answers

You can use json_encode($data, JSON_PRETTY_PRINT) in php 5.4+

In php 5.3 & under that, you could try formatting it with regular expressions, but it's not too safe (or you could use library for encoding json).

like image 43
pozs Avatar answered Dec 05 '22 23:12

pozs


The first piece of advice I'd give is: Don't. JSON is a data format. Deal with it using tools rather then trying to have your server format it.

If you are going to ignore that, then see the manual for the json_encode function where it gives a list of options which includes JSON_PRETTY_PRINT which is described as Use whitespace in returned data to format it. Available since PHP 5.4.0.

Thus the steps are:

  1. Make sure you are using PHP 5.4.0 or newer
  2. json_encode($data, JSON_PRETTY_PRINT);
like image 149
Quentin Avatar answered Dec 05 '22 23:12

Quentin