Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Cant set JSON utf-8 charset

I have a specific problem in Laravel .

When I use echo or print_r or var_dump my data (retrieved from eloquent) are printed in the right format (UTF-8, greek language). But when I use

return Response::json($data)

returns something like

"\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03bf\u03af \u03c7\u03b1\u03c1\u03b1\u03ba\u03c4\u03ae\u03c1\u03b5\u03c2"

I have already set UTF-8 as default charset in my php.ini, mysql.conf (but this is not the problem).

I have tried several ways to set the charset like:

Response::json($data,200,$headers)

where $headers is an array with:

'Content-type'=> 'application/json; charset=utf-8'

But nothing changes.

My operating system is Debian 7 wheezy 64bit, PHP version 5.5.13 , MySQL 5.6.19 and apache2 server.

like image 278
user2718934 Avatar asked Feb 12 '23 15:02

user2718934


2 Answers

JSON_UNESCAPED_UNICODE didn't work without the right header set like this for me:

return Response::json($data, 200, array('Content-Type' => 'application/json;charset=utf8'), JSON_UNESCAPED_UNICODE);

After the header Content-Type was set to application/json;charset=utf8 it did work for me.

Works with current Laravel Version. (5.4)

like image 88
DominikAngerer Avatar answered Feb 15 '23 09:02

DominikAngerer


From Laravel 4.1, you can specify json_encode() options as the 4th parameter on the method below. You will want to pass the JSON_UNESCAPED_UNICODE option to escape the utf-8 text

Response::json($data, 200, $headers, JSON_UNESCAPED_UNICODE);

This function will pass the options through when it calls json_encode()

http://php.net/manual/en/function.json-encode.php

like image 21
dsturbid Avatar answered Feb 15 '23 10:02

dsturbid