Search code examples
phpjsonslim

Slim Framework Pretty JSON


How to configure Slim Framework to output pretty JSON?

In PHP native I could do it using this syntax

json_encode($data, JSON_PRETTY_PRINT);

Solution

  • Quoting from Slim docs:

    Slim’s Response object has a custom method withJson($data, $status, $encodingOptions) to help simplify the process of returning JSON data.

    The $data parameter contains the data structure you wish returned as JSON. $status is optional, and can be used to return a custom HTTP code. $encodingOptions is optional, and are the same encoding options used for json_encode().

    So, if you're using withJson to return JSON response you can use it like:

    return $response->withJson($data, 200, JSON_PRETTY_PRINT);