简体   繁体   中英

UTF-8 characters don't display correctly

This is my PHP code:

<?php
$result = '';
$str = 'Тугайный соловей';
for ($y=0; $y < strlen($str); $y++) {
    $tmp = mb_substr($str, $y, 1);
    $result = $result . $tmp;
}
echo 'result = ' . $result;

The output is:

Тугайный Ñоловей

What can I do? I have to put $result into a MySQL database.

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.

如果您要发送混合数据并且不想使用 php 标头指定 utf-8,则可以将此 html 添加到您的页面:

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

我想,您的代码采用windows-1251编码,因为它是俄语 :) 将您的字符串转换为 utf-8:

$str = iconv('windows-1251', 'utf-8', $str);

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');

只需在与服务器连接后的开头添加此行:

mysqli_set_charset($conn,"utf8");

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");

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM