Skip to content

Instantly share code, notes, and snippets.

@floutchito
Forked from omnidan/PrettyJsonResponse.php
Last active November 16, 2015 18:07
Show Gist options
  • Save floutchito/d7481df4a6f353136afe to your computer and use it in GitHub Desktop.
Save floutchito/d7481df4a6f353136afe to your computer and use it in GitHub Desktop.
<?php
/**
* @license WTFPL (Do What the Fuck You Want to Public License)
* @author Daniel Bugl <daniel.bugl@touchlay.com>
*/
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);

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