Having trouble with Php, Mysql and UTF8

2019-02-25 01:00发布

问题:

Problem, simple and annoying.


Im just trying to print a list of names, collected from my mysql database.

The PHP-files are saved in utf8, the database and tables are set to use utf8. Still 'å,ä,ö', for example, outputs as �. Can't believe I'm still having this issue.

Of course, Latin1 solves the problem. The thing is that I have to use utf8 since I'm doing some json_encode for sending the data to an ajax-script.

Any idea what on earth could be wrong?

Should I convert the data to utf8 before returning it perhaps? Seems weird I should have to..

回答1:

Convert utf8_general_ci to utf8_unicode_ci...

Try running SET NAMES UTF8 query after you connect to database...

function connect($server, $database, $username, $password, $charset = "UTF8"){
    $link = mysql_connect($server, $database, $password);
    if(!$link){
        die("Unable to connect to database server.");
    }
    mysql_selectdb($database);
    if(function_exists("mysql_set_charset")){
        mysql_set_charset($charset, $link);
    }else{
        mysql_query("SET NAMES $charset");   
    }
}

Also make sure you have this (or via header()) in your HTML...

<meta http-equiv="content-type" content="text/html; charset=utf-8" />


回答2:

Two things to do...

  1. Make sure your HTML header is sending the correct charset:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

  2. Use utf_encode() when adding your names to the array. The line in your should be

    $guests[] = array_map('utf8_encode', $row);