Echo json_encode format

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"}]]}}} 

While I would like 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 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 JSON, but the header also outputs the entire HTML document

+4
source share
2 answers

The first piece of advice I would give is: Don't. JSON is a data format. Process it with tools, and then try to have your server format it.

If you ignore this, refer to the manual for the json_encode function, where it gives a list of options, which includes JSON_PRETTY_PRINT , which describes how to use a space in the returned data to format it. Available since PHP 5.4.0.

So the steps are:

  • Make sure you are using PHP 5.4.0 or later
  • json_encode($data, JSON_PRETTY_PRINT);
+12
source

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

In php 5.3 and below, you can try formatting it with regular expressions, but it is not too safe (or you can use the library to encode json).

+1
source

All Articles