UTF-8 字符无法正确显示
这是我的 PHP 代码:
<?php
$result = '';
$str = 'Тугайный соловей';
for ($y=0; $y < strlen($str); $y++) {
$tmp = mb_substr($str, $y, 1);
$result = $result . $tmp;
}
echo 'result = ' . $result;
输出是:
Тугайный Ñоловей
我能做什么?我必须将 $result
放入 MySQL 数据库中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你的文件的编码是什么?也应该是UTF8。你的http服务器的默认字符集是什么?它也应该是UTF-8。
编码仅在以下情况下有效:
使用数据库时,您还必须为数据库字段以及 MySQL 客户端与服务器通信的方式设置正确的编码(请参阅 mysql_set_charset() )。仅字段是不够的,因为您的 MySQL 客户端(在本例中为 PHP)可能默认设置为 ISO 并重新解释数据。所以你最终得到 UTF8 DB -> ISO客户端->注入到 UTF8 PHP 脚本中。难怪最后为什么会搞砸:-)
如何使用正确的字符集提供文件?
header('Content-type: text/html; charset=utf-8')
是一种解决方案。包含
AddDefaultCharset UTF-8
的 htaccess 文件是另一种HTML 元内容 - type 也可能有效,但最好使用 HTTP 标头发送此信息。
PS:您还必须使用
mb_strlen()
因为 UTF8 字符串上的strlen()
报告的长度可能会超过实际长度。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:
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 oneHTML 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()
becausestrlen()
on UTF8 strings will probably report more than the real length.如果您要发送混合数据并且不想使用 php 标头指定 utf-8,则可以将此 html 添加到您的页面:
If you're going to send a mix of data and don't want to specify utf-8 using a php header, you can add this html to your page:
我想,您的代码采用
windows-1251
编码,因为它是俄语:)将字符串转换为 utf-8:
I suppose, your code is in
windows-1251
encoding since it is Russian :)convert your string to utf-8:
如果你的数据库是UTF-8的话,mysql就可以了。
对于您的回声,如果您在网站中执行此操作,请将其放在首页中:
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:
只需在与服务器连接后的开头添加此行:
Just add this line at the beginning, after the connection with server:
试试这个:
try this:
如果你只是使用 PHP echo 而不使用 HTML headers 等,这对我来说非常有用。
if you are just using PHP echo with no HTML headers etc., this worked great for me.