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
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).
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:
json_encode($data, JSON_PRETTY_PRINT);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With