UTF-8转换数据[重复]

This question already has an answer here:

I use ZF2 and a mysql database. The problem is the data are latin1 encoded, but for the moment I don't have to change that. So I use a lot of tricks to force my PDO driver to have my results on UTF-8 :

This one in local.php :

return array(
    'db' => array(
        'username' =>  $dbParams['username'],
        'dsn'      => 'mysql:dbname='.$dbParams['database'].';host='.$dbParams['hostname'].';charset=utf-8',
        'password' => '',
        'charset'  => 'utf-8',
    ),
);

And this one in global.php

return array(
    'db' => array(
        'charset'  => 'utf-8',
        'driver' => 'Pdo',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8",
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET UTF8",
         ),
    ),
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        )
    ),
    'translator' => array(
        'locale' => 'fr_FR'
    ),
);

But when I do :

echo "ENCODING=".mb_detect_encoding($myDataBaseRetrievedVar);

This tells me : ASCII ! And for special characters I can't do a json_encode.

</div>

First, for mysql, encoding is called utf8, not utf-8.

Second, basic latin1 characters are the same in utf-8. Means 'Amelie' in utf-8 is the same string as 'Amelie' in latin1 as well as ASCII. Means having 'Amelie' in ASCII you have it in utf-8 as well.

Third, latin1 supports limited amount of "special characters" and you simply cannot expect from a single-byte encoding the same number of characters supported as from the multi-byte one.

A meta note: if you have particular problem with particular function, you have to ask the question regarding this particular problem, not something else. Otherwise no answer will be good for you.

In case you have a problem with json_encode(), you have to supply with your question:

  • the code
  • the exact error message
  • the data sample

And only after solving this problem, you may proceed to the database interaction, that may be the cause for the problem. In programming, no solution can be found based on a guess.