Home > Software design >  Emulate Replacer and Space from JS's JSON.stringify() in PHP with json_encode()?
Emulate Replacer and Space from JS's JSON.stringify() in PHP with json_encode()?

Time:09-25

In JS you can stringify an array with two other arguments (replacer and space) which create a new line for each object within the array. This is useful for human readable format when writing to a file.

JSON.stringify(array, null, 2);

How can I emulate this replacer and space behavior in PHP?

json_encode($array, null, 2);

Currently, my json_encoded array data writes to a single line, how can I write it to multiple lines in a good format?

//Currently json_decode writes to file like this
[{"test": "test"},{"test": "test"}]

//But I want it to write to the file like this.
[
  {
    "test": "test"
  },
  {
    "test": "test"
  },
]

CodePudding user response:

You can pass the flag JSON_PRETTY_PRINT to the json_encode function.

json_encode($array, JSON_PRETTY_PRINT);

The output will not be exactly the same as from javascript, but it is much easier to read. For further reading on the JSON constants: https://www.php.net/manual/en/json.constants.php

  • Related