How to get symfony to specify its encoding in all responses?

All responses from my Symfony 2 application have the following header line:

Content-Type: text/html 

Therefore, my browser assumes the output encoding is ISO-8859-1. I would like the headline to say:

 Content-Type: text/html; charset=utf8 

instead of this. I know I can do it manually for every answer like this:

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

But that would be incredibly redundant, since my application has many controls and will only output UTF-8. I searched in vain for setting up a symfony configuration that controls the default encoding. I found framework.charset , but it seems to be unrelated, and by default it is UTF-8.

How to get symfony to specify my encoding in all answers?


My thoughts

I know this is not a very big problem (most of the time), since I can explicitly specify the encoding in both HTML and XML. The problem is that I am serving plain text or JSON, or I am resetting variables with var_dump . In both cases, all non-ASCII characters are scrambled as my browser makes an erroneous guess.

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

+6
source share
4 answers

Using setCharset () does not set the encoding in the headers .

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

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

Also, if you want your json output to display 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 also prints as well :)

+1
source

If nothing else helps, keep using $response->setCharset('UTF-8'); but put it in the kernel response listener. This is a common pattern in Symfony: every time you do (almost) the same thing in multiple controllers, it should go to the kernel response listener instead of holding the controller code directly at a point.

0
source

In Symfony 3.1, just override getCharset () in AppKernel. http://symfony.com/doc/current/reference/configuration/kernel.html

 // app/AppKernel.php // ... class AppKernel extends Kernel { public function getCharset() { return 'ISO-8859-1'; } } 
0
source

I think you can say a framework that encodes for use in your config.yml:

 framework: charset: UTF-8 

See: http://symfony.com/doc/current/reference/configuration/framework.html

-1
source

Source: https://habr.com/ru/post/944939/


All Articles