开发者

How can I pretty format JSON output in CakePHP?

I would like my JSON output in CakePHP to be "pretty" or nicely formatted.

Right now, I call the $javascript->object method a开发者_高级运维nd my JSON is all on one line.

At times this can be difficult to see if there is a problem in the JSON output stream.


You can preserve formatting with a html <pre> tag, which tells the browser that the text has been pre-formatted:

<pre><?php echo $javascript->object; ?></pre>


you might consider this: Format JSON with PHP

and then echo '<pre>'.indent(json_encode(your_array)).'</pre>';


For CakePHP 3.0+, you would use the _jsonOptions to set JSON_PRETTY_PRINT (along with any other json settings you would might need using a bitwise OR | operator)

$this->set('_jsonOptions', JSON_PRETTY_PRINT);
$this->RequestHandler->renderAs($this, 'json');
$this->set(compact('myData'));
$this->set('_serialize', ['myData']);

Other json options you can set can be found here: https://www.php.net/manual/en/json.constants.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜