سؤال

I'm developing a web application with Symfony and MySQL as database. My database creation syntax is as below:

CREATE DATABASE `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

The table which I need to know why is returning unexpected text is:

CREATE TABLE `elements` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL
)ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

And the entity code in PHP is:

/**
 * 
 *
 * @ORM\Table(name="elements")
 * @ORM\Entity()
 */
class Element
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=100)
     */
    private $name;
}

When the name of the Element has Spanish characters like á,é,í,ó,ú,ñ; in the browser is correctly rendered, and in the database the characters are stored in this way, but when I try to return this information using a JsonResponse, the characters are converted to others codes. For example:

$result['id']       = $e->getId();
$result['name']     = $e->getName();

return new JsonResponse( array('response' => $result) );

And the response shows:

"response":{
    "id":26,
    "name":"Avi\u00f3n"
}

And name should be "Avión" instead.

I would like to know why this happens and how can avoid this behavior. Any ideas?

Thanks in advance.

هل كانت مفيدة؟

المحلول 2

When you called new JsonResponse($data), among other things, your data is encoded in this way:

json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);

By default, json_encode escapes unicode characters, so the output you get is the expected one. If you don't want to have your unicode escaped, you can create your controller response as follow:

$data = array('response' => $result);
return new Response( json_encode($data, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT));

نصائح أخرى

I don't see actual problem here.

They are not converted to other codes.

Instead, they are utf-8 encoded (default JSON encoding).

Some info : RFC4627 section 2.5 strings

\u00F3 is utf-8 encoded character ó, see here

UPDATE:

Read this : JSON Encoding and decoding of UTF8 characters in PHP

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top