UTF-8 characters don't display correctly

前端 未结 7 1121
清酒与你
清酒与你 2020-12-11 02:41

This is my PHP code:



        
相关标签:
7条回答
  • 2020-12-11 02:48

    What's the encoding of your file? It should be UTF8 too. What's the default charset of your http server? It should be UTF-8 as well.

    Encoding only works if:

    • the file is encoded correctly
    • the server tells what's the encoding of the delivered file.

    When working with databases, you also have to set the right encoding for your DB fields and the way the MySQL client communicates with the server (see mysql_set_charset()). Fields only are not enough because your MySQL client (in this case, PHP) could be set to ISO by default and reinterprets the data. So you end up with UTF8 DB -> ISO client -> injected into UTF8 PHP script. No wonder why it's messed up at the end :-)

    How to serve the file with the right charset?

    header('Content-type: text/html; charset=utf-8') is one solution

    .htaccess file containing AddDefaultCharset UTF-8 is another one

    HTML meta content-type might work too but it's always better to send this information using HTTP headers.

    PS: you also have to use mb_strlen() because strlen() on UTF8 strings will probably report more than the real length.

    0 讨论(0)
  • 2020-12-11 02:49

    try this:

        header('Content-Type: text/html; charset=UTF-8');
        header("Content-type: application/octetstream");
        header("Pragma: no-cache");
        header("Expires: 0");
        //print "$name_field\n$data";
    
        // با این کد درست شد
        print chr(255) . chr(254) . mb_convert_encoding("$name_field\n$data", 'UTF-16LE', 'UTF-8');
    
    0 讨论(0)
  • 2020-12-11 02:50

    if you are just using php echo with no html headers etc., this worked great for me.

    $connect = mysqli_connect($host_name, $user_name, $password, $database); mysqli_set_charset($connect,"utf8");

    0 讨论(0)
  • 2020-12-11 02:52

    I suppose, your code is in windows-1251 encoding since it is Russian :) convert your string to utf-8:

    $str = iconv('windows-1251', 'utf-8', $str);
    
    0 讨论(0)
  • 2020-12-11 02:56

    Just add this line at the beginning, after the connection with server:

    mysqli_set_charset($conn,"utf8");
    
    0 讨论(0)
  • 2020-12-11 03:06

    If your database is UTF-8, it's ok for mysql.

    For your echo, if you do it in a web site, put this in the top page:

    header('Content-Type: text/html; charset=UTF-8');
    
    0 讨论(0)
提交回复
热议问题