문제

Now I, in my own opionion, have tried everything there is on this encoding problem, looked through a lot of answered quistions but nothing worked for me, so here I go.

I have a MySQL database with a Users table. This table has a column for "firstname" which collation is set to utf8_general_ci (all varchar columns is). I have then inserted a row where the firstname-column is set to "Løw", with the scandinavian special character "ø".

I now use the php-ActiveRecord library, where the connection string is to ";charset=utf8", to retrieve the row and afterwards outputs the user as json, like so:

$user = User::find($ID);
$userArr = $user->to_array();
header('Content-Type: application/json; charset=utf-8');
print(json_encode($userArr));

Now the wired things starts. The firstname is now NOT "Løw" as displayed in the MySQL Database , but "L\u00f8w". I then tried to see if this was also the case without the json_encode function, like so:

$user = User::find($ID);
$userArr = $user->to_array();
header('Content-Type: text/plain; charset=utf-8');
print_r($userArr);

But here the output was correct, firstname was "Løw". I then tried to encode the fields in the array to utf-8, since everybody told me if the strings was utf-8 it should work, like so:

$return[] = array_map('utf8_encode', $userArr);
print_r(json_encode($return));

But this gave me "L\u00c3\u00b8w", so that didn't work. I then tried, since i was out of ideas to utf8_decode it:

$return[] = array_map('utf8_decode', $userArr);
print_r(json_encode($return));

But that made the string return as "null". I then tried to check what encoding my vars was when they came out of the database, like so:

header('Content-Type: text/plain; charset=utf-8');
print(mb_detect_encoding($userArr['firstname']));

But this returned UTF-8.

So as you, hopefully, can see, i have tried everything and i still don't know why my json_encode, changes the "ø" charcter to "\u00f8". Please help, i don't want to make my own json_encode-method.

도움이 되었습니까?

해결책

Ok found an answer pretty quick, but ill let other scandinavian people know, since i coulden't find anything on the subject.

I solved the problem by adding the following to the json_encode method:

print(json_encode($userArr,JSON_UNESCAPED_UNICODE));

This tells the method NOT to escape unicode chars (i think) or as it says in the PHP doc:

JSON_UNESCAPED_UNICODE (integer)

Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top