3

I've seen multiple answers in here but none of them had a solution to my question, so I made an account to ask this question. I understand now that \n is not an allowed character in json because the backslash is not allowed and that's why the problem is occurring.

I have the following code to encode an array in json:

<?php
$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
echo json_encode($data);

I'm trying to have the string outputted as follows:

{

"test1": "something1",

"test2": "something2",

"test3": "something3"

}

But what I'm getting is this:

{"test1":"something1","test2":"something2","test3":"something3"}

This is my go at it:

<?php
$data = array('test1' => 'something1\n', 'test2' => 'something2\n', 'test3' => 'something3\n');
echo json_encode($data);

but this returns

{"test1":"something1\n","test2":"something2\n","test3":"something3\n"}

Community
  • 1
  • 1

3 Answers3

3

You can add a second parameter to json_encode. This is called the JSON_PRETTY_PRINT constant:

<?php
$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
echo json_encode($data, JSON_PRETTY_PRINT);
Daan
  • 12,099
  • 6
  • 34
  • 51
0

You can use JSON_PRETTY_PRINT with header

$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data,JSON_PRETTY_PRINT);

OR

$json= json_encode($data,JSON_PRETTY_PRINT);
printf("<pre>%s</pre>", $json);
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

JSON is an interchange format, so you need not to be concerned about the looks very much.

Anyway, you can use flag constants to alter the encoding process

<?php

$a = '{"test1":"something1","test2":"something2","test3":"something3"}';
print_r(json_encode(json_decode($a, true), JSON_PRETTY_PRINT));

See live example: https://3v4l.org/CEc3L

helvete
  • 2,455
  • 13
  • 33
  • 37