Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Symfony to specify my charset in all responses?

Tags:

php

symfony

All responses from my Symfony 2 application all have this header line:

Content-Type: text/html

So my browser assumes the output charset is ISO-8859-1. I would like the header to say:

Content-Type: text/html; charset=utf8

instead. I know I can do this manually for every response like this:

$response->setCharset('UTF-8');

But that would be incredibly redundant since my application has lots of controls and will only ever output UTF-8. I have searched in vain for a Symfony configuration setting that controls the default charset. I found framework.charset but that seems to be unrelated, and is UTF-8 by default anyway.

How do I get Symfony to specify my charset in all responses?


My thoughts

I know this isn't too much of a problem (most of the time) since I can specify the charset explicitly in both HTML and XML. The issue is when I'm service plain text or JSON, or if I'm dumping variables using var_dump. In both cases, all non-ASCII symbols are scrambled as my browser ventures an erroneous guess.

My backup solution is to subclass the response class and put $this->setCharset('UTF-8') in the constructor.

like image 401
Hubro Avatar asked May 14 '13 00:05

Hubro


1 Answers

Using setCharset() doesn't set charset in headers.

If you want to specify utf-8 encoding in headers, you can use following code somewhere before $app->run()

$app->after(
    function (Request $request, Response $response) {
        $response->headers->set(
            'Content-Type', 
            $response->headers->get('Content-Type') . '; charset=UTF-8'
        );

        return $response;
    }
);

Additionally if you want your json output to be displayed with unescaped utf8 characters, you can use something like this:

$app->after(
    function (Request $request, Response $response) {
        $response->headers->set('Content-Type', $response->headers->get('Content-Type') . '; charset=UTF-8');

        if ($response instanceof JsonResponse) {
            $response->setEncodingOptions(JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }

        return $response;
    }
);

It sets pretty print as well :)

like image 78
Konrad Gałęzowski Avatar answered Sep 22 '22 09:09

Konrad Gałęzowski