Skip to content

Instantly share code, notes, and snippets.

@omnidan
Last active July 17, 2019 12:48
Show Gist options
  • Save omnidan/7706595 to your computer and use it in GitHub Desktop.
Save omnidan/7706595 to your computer and use it in GitHub Desktop.
Pretty-printed Symfony JsonResponse class. 100% compatible with the original class, requires PHP 5.4.0 or higher.
<?php
/**
* @license WTFPL (Do What the Fuck You Want to Public License)
* @author Daniel Bugl <[email protected]>
*/
namespace TouchLay\HelperBundle\Component;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Class PrettyJsonResponse: Pretty prints the Symfony JsonResponse, 100% compatible with JsonResponse
* @package TouchLay\HelperBundle\Component
*/
class PrettyJsonResponse extends JsonResponse {
/**
* Sets the data to be sent as json.
*
* @param mixed $data
*
* @return JsonResponse
*/
public function setData($data = array())
{
// Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
$this->data = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
| JSON_PRETTY_PRINT); // JSON_PRETTY_PRINT requires PHP >5.4.0
return $this->update();
}
}
@Potherca
Copy link

It may not have been possible when this gist was written, but you can just set the encoding on the JsonResponse object:

$response = new \Symfony\Component\HttpFoundation\JsonResponse();
$response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT);

@erkineren
Copy link

erkineren commented Nov 23, 2018

Just extend JsonResponse end override property,

class PrettyJsonResponse extends JsonResponse
{
    protected $encodingOptions = parent::DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment