N
N
notmad2019-05-04 21:21:49
PHP
notmad, 2019-05-04 21:21:49

Problems with encoding. Why does php return Russian letters as u041f?

After a query in mysql it returns an associative array, in mysql the comparison is utf8_unicode_ci after json_encode() I get the following array: [{"reportId":"1","title":"?????? ?????"} ] , since instead of Cyrillic question marks it is immediately clear that the problem is in the encoding, I add this code after connecting to the database:

$con->query("SET NAMES 'utf8'"); 
$con->query("SET CHARACTER SET utf8");  
$con->query("SET SESSION collation_connection = 'utf8_unicode_ci'");

and now php page returns this:
[{"reportId":"1","title":"\u041f\u0435\u0440\u0432\u044b\u0439 \u043e\u0442\u0447\u0435\u0442"}]
options like this I did not find a fix, I will be grateful for any help.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Dmitry, 2019-05-04
@notmad

We take your line and process
At the output we get

Array
(
    [0] => Array
        (
            [reportId] => 1
            [title] => Первый отчет
        )

)

Or
And the output is the usual array
Array
(
    [reportId] => 1
    [title] => Первый отчет
)

What do you want to fix in this case?

F
FanatPHP, 2019-05-04
@FanatPHP

1. Why fix it?
2. If you call on logic to help, then you can guess that such an output is returned not by a "php page" but by a certain function. And if you open the description of this function in the manual once in a lifetime, then you wouldn’t have to look for a solution, since it is written there in Russian in white

P
profesor08, 2019-05-04
@profesor08

Something translates Russian letters into this form. Find out what this piece of code is and fix it. Perhaps the text in this form is in your database. Then find the function that writes to the database and fix it. If you do not want to think and solve the problem, then suffer the consequences.

function replace_unicode_escape_sequence($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}

function unicode_decode($str) {
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $str);
}

echo unicode_decode("\u041f\u0435\u0440\u0432\u044b\u0439 \u043e\u0442\u0447\u0435\u0442");

S
synapse_people, 2019-05-04
@synapse_people

[{"reportId":"1","title":"\u041f\u0435\u0440\u0432\u044b\u0439 \u043e\u0442\u0447\u0435\u0442"}] only this should be the correct answer

S
Sergey Yakovlev, 2019-05-05
@sergeyakovlev

and now the php page returns this:
[{"reportId":"1","title":"\u041f\u0435\u0440\u0432\u044b\u0439 \u043e\u0442\u0447\u0435\u0442"}]

If you use json_encode($report, JSON_UNESCAPED_UNICODE), then the output will be a readable test.
The correctness of the result can be checked by simply displaying the value of the field:
echo $report['title'];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question