Home php教程 php手册 PHP乱码问题,UTF-8乱码常见问题小结

PHP乱码问题,UTF-8乱码常见问题小结

Jun 13, 2016 pm 12:00 PM
head php ti utf-8 one Garbled characters back exist common problem coding change question page

一.HTML页面转UTF-8编码问题
1.在head后,title前加入一行:


顺序不能错,一定要在

显示的标题有可能是乱码!

2.html文件编码问题:

点击编辑器的菜单:“文件”->“另存为”,可以看到当前文件的编码,确保文件编码为:UTF-8,
如果是ANSI,需要将编码改成:UTF-8。
3.HTML文件头BOM问题:
将文件从其他的编码转换成UTF-8编码时,有时候会在文件的最开始加上一个BOM标签,
在个BOM标签可能会导致浏览器在显示中文的时候出现乱码。
删除这个BOM标签的方法:
1.可以用Dreamweaver打开文件,并重新保存,即可以去除BOM标签!
2.可以用EditPlus打开文件,并在菜单“首选项”->“文件”->"UTF-8标识",设置为:“总是删除签名”,
然后保存文件,即可以去除BOM标签!
4.WEB服务器UTF-8编码问题:
如果你按以上所列的步骤做了,还是有中文乱码问题,
请检查你的所使用的WEB服务器的编码问题
如果你使用的是Apache,请将配置文件里的:charset 设成:utf-8(这里仅列出方法,具体格式请参考apache的配置文件)
如果你使用的是Nginx,请将nginx.conf里的:charset 设成 utf-8,
具体找到 "charset gb2312;"或者类似的语句,改成:“charset utf-8;”。
二.PHP页面转UTF-8编码问题
1.在代码开始出加入一行:
header("Content-Type: text/html;charset=utf-8");

2.PHP文件编码问题

点击编辑器的菜单:“文件”->“另存为”,可以看到当前文件的编码,确保文件编码为:UTF-8,
如果是ANSI,需要将编码改成:UTF-8。
3.PHP文件头BOM问题:
PHP文件一定不可以有BOM标签
否则,会出现session不能使用的情况,并有类似的提示:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent
这是因为,在执行session_start() 的时候,整个页面不能有输出,但是当由于前PHP页面存在BOM标签,
PHP把这个BOM标签当成是输出了,所以就出错了!
所以PHP页面一定要删除BOM标签
删除这个BOM标签的方法:
1.可以用Dreamweaver打开文件,并重新保存,即可以去除BOM标签!
2.可以用EditPlus打开文件,并在菜单“首选项”->“文件”->"UTF-8标识",设置为:“总是删除签名”,
然后保存文件,即可以去除BOM标签!
4.PHP以附件形式保存文件的时候,UTF-8编码问题:
PHP以附件形式保存文件,文件名必须是GB2312编码,
否则,如果文件名中有中文的话,将是显示乱码:
如果你的PHP本身是UTF-8编码格式的文件,
需要将文件名变量由UTF-8转成GB2312:
iconv("UTF-8", "GB2312", "$filename");

5.截断显示文章标题时,出现乱码或者“?”问号的问题:
一般文章标题很长的时候,会显示一部分标题,会对文章标题进行截断,
由于一个UTF-8编码格式的中文字符会占用3个字符宽度,
截取标题的时候,有时会只截取到一个中文字符的1个字符或2字符宽度,
没截取完整,将出现乱码或“?”问号的情况,
用下面的函数截取标题,就不会有问题:

复制代码 代码如下:


function get_brief_str($str, $max_length)
{
echo strlen($str) ."
";
if(strlen($str) > $max_length)
{
$check_num = 0;
for($i=0; $i {
if (ord($str[$i]) > 128)
$check_num++;
}

if($check_num % 3 == 0)
$str = substr($str, 0, $max_length)."...";
else if($check_num % 3 == 1)
$str = substr($str, 0, $max_length + 2)."...";
else if($check_num % 3 == 2)
$str = substr($str, 0, $max_length + 1)."...";
}
return $str;
}


三.MYSQL数据库使用UTF-8编码的问题

1.用phpmyadmin创建数据库和数据表
创建数据库的时候,请将“整理”设置为:“utf8_general_ci”
或执行语句:

CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
创建数据表的时候:如果是该字段是存放中文的话,则需要将“整理”设置为:“utf8_general_ci”,

如果该字段是存放英文或数字的话,默认就可以了。

相应的SQL语句,例如:

复制代码 代码如下:


CREATE TABLE `test` (
`id` INT NOT NULL ,
`name` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;


2.用PHP读写数据库

在连接数据库之后:

[hide]$connection = mysql_connect($host_name, $host_user, $host_pass);

加入两行:

复制代码 代码如下:


mysql_query("set character set 'utf8'");//读库
mysql_query("set names 'utf8'");//写库


就可以正常的读写MYSQL数据库了。

四.JS相关的UTF-8编码问题
1.JS读Cookie的中文乱码问题

PHP写cookie的时候需要将中文字符进行escape编码,
否则JS读到cookie中的中文字符将是乱码。
但php本身没有escape函数,我们新写一个escape函数:

复制代码 代码如下:


function escape($str)
{
preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v)
{
if(ord($v[0]) $ar[$k] = rawurlencode($v);
else
$ar[$k] = "%u".bin2hex(iconv("UTF-8","UCS-2",$v));
}
return join("",$ar);
}


JS读cookie的时候,用unescape解码,

然后就解决cookie中有中文乱码的问题了。

2.外部JS文件UTF-8编码问题

当一个HTML页面或则PHP页面包含一个外部的JS文件时,

如果HTML页面或则PHP页面是UTF-8编码格式的文件,

外部的JS文件同样要转成UTF-8的文件,

否则将出现,没有包含不成功,调用函数时没有反应的情况。

点击编辑器的菜单:“文件”->“另存为”,可以看到当前文件的编码,确保文件编码为:UTF-8,

如果是ANSI,需要将编码改成:UTF-8。

五.FLASH相关的UTF-8编码问题

FLASH内部对所有字符串,默认都是以UTF-8处理
1.FLASH读文普通本文件(txt,html)
要将文本文件的编码存为UTF-8
点击编辑器的菜单:“文件”->“另存为”,可以看到当前文件的编码,确保文件编码为:UTF-8,
如果是ANSI,需要将编码改成:UTF-8。
2.FLASH读XML文件
要将XML文件的编码存为UTF-8
点击编辑器的菜单:“文件”->“另存为”,可以看到当前文件的编码,确保文件编码为:UTF-8,
如果是ANSI,需要将编码改成:UTF-8。
在XML第1行写:

3.FLASH读PHP返回数据
如果PHP编码本身是UTF-8的,直接echo就可以了
如果PHP编码本身是GB2312的,可以将PHP转存成UTF-8编码格式的文件,直接echo就可以了
如果PHP编码本身是GB2312的,而且不允许改文件的编码格式,
用下面的语句将字符串转换成UTF-8的编码格式
$new_str = iconv("GB2312", "UTF-8", "$str");
再echo就可以了
4.FLASH读数据库(MYSQL)的数据
FLASH要通过PHP读取数据库中的数据
PHP本身的编码不重要,关键是如果数据库的编码是GB2312的话,
需要用下面的语句将字符串转换成UTF-8的编码格式
$new_str = iconv("GB2312", "UTF-8", "$str");

5.FLASH通过PHP写数据
一句话,FLASH传过来的字符串是UTF-8格式的,
要转换成相应的编码格式,再操作(写文件、写数据库、直接显示等等)
还是用iconv函数转换
6.FLASH使用本地编码(理论上不推荐使用)
如果想让FLASH不使用UTF-8编码,而是使用本地编码
对于中国大陆地区而言,本地编码是GB2312或GBK
AS程序内,可以添加以下代码:
System.useCodepage = true;
那么FLASH内所有字符都是使用GB2312的编码了
所有导入到FLASH或者从FLASH导出的数据,都应该做相应的编码转换
因为使用本地编码,会造成使用繁体中文地区的用户产生乱码,所以不推荐使用
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles