A
A
Artur Bekerov2014-01-08 11:00:16
PHP
Artur Bekerov, 2014-01-08 11:00:16

Why does the slim framework render Cyrillic incorrectly?

I am developing a backend on a slim framework.
The data is given in json like

{name:"\u0414\u0436\u0438\u0414\u0438\u0421\u0438 \u0421\u0435\u0440\u0432\u0438\u0441\u0435\u0437"}

It would be desirable that the data was transferred normally.
1) Here is an example application
$app = new \Slim\Slim();
//Company handle
$app->contentType('text/html; charset=utf-8');

2) in connection with the base, the encoding is also indicated
function getConnection() {
    $dbhost="";
    $dbuser="";
    $dbpass="";
    $dbname="crm";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
    $dbh->exec("set names utf8");
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}

3) All files are saved in UTF8
4) The data in the database is also stored in utf8
I don’t understand where the plug is. Is this how the data should be transferred?
I would be grateful for help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily, 2014-01-08
@krekerov

So, this is how json_encode works in PHP, it's a unicode sequence.
A crutch: if you have a new PHP (starting from PHP 5.4.0.) find in the framework where json_encode is used and use json_encode($data, JSON_UNESCAPED_UNICODE);
If PHP is old then you can use your encoder:

public function to_json($data) {
        if ($data === null) {
            $data = [];
        }
        $isArray = true;
        $keys = array_keys($data);
        $prevKey = -1;
        foreach ($keys as $key)
            if (!is_numeric($key) || $prevKey + 1 != $key) {
                $isArray = false;
                break;
            } else
                $prevKey++;
        unset($keys);
        $items = array();
        foreach ($data as $key => $value) {
            $item = (!$isArray ? "\"$key\":" : '');
            if (is_array($value))
                $item .= $this->to_json($value);
            elseif (is_null($value))
                $item .= 'null';
            elseif (is_bool($value))
                $item .= $value ? 'true' : 'false';
            elseif (is_string($value))
                $item .= '"' . preg_replace('%([\\x00-\\x1f\\x22\\x5c])%e', 'sprintf("\\\\u%04X", ord("$1"))', $value) . '"';
            elseif (is_numeric($value))
                $item .= $value;
            else
                throw new Exception('Wrong argument.');
            $items[] = $item;
        }
        return ($isArray ? '[' : '{') . implode(',', $items) . ($isArray ? ']' : '}');
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question