search
HomeBackend DevelopmentPHP ProblemHow to solve php Chinese garbled characters

How to solve php Chinese garbled characters

##Recommended manual: php complete self-study manual
##1. Check the problem of converting the HTML page to UTF-8 encoding

1. After the head, add a line before the title:

<meta http-equiv=&#39;Content-Type&#39; content=&#39;text/html; charset=utf-8&#39; />

The order cannot be wrong, it must be after the head, before title.

2.html file encoding problem:

Click the editor's menu: "File"->"Save As", you can see the encoding of the current file, make sure the file encoding is: UTF -8,

If it is ANSI, you need to change the encoding to: UTF-8.

3. HTML file header BOM problem:

When converting a file from other encodings to UTF-8 encoding, sometimes a BOM tag is added at the beginning of the file,

A BOM tag may cause the browser to display garbled characters when displaying Chinese characters.

Methods to delete this BOM tag:

(1) You can open the file with Dreamweaver and resave it to remove the BOM tag!

(2) You can open the file with EditPlus, and in the menu "Preferences"->"File"->"UTF-8 Identity", set it to: "Always delete signature",

Then save the file and you can remove the BOM tag!

4. WEB server UTF-8 encoding problem:

If you follow the steps listed above and still have Chinese garbled problems, please check the encoding of the WEB server you are using. question.

If you are using Apache, please set the charset in the configuration file to: utf-8 (only the methods are listed here, please refer to the apache configuration file for the specific format)

If You are using Nginx. Please set charset in nginx.conf to utf-8. Specifically, find "charset gb2312;" or a similar statement and change it to: "charset utf-8;".

Related recommendations: "

PHP Tutorial

"

2. Converting PHP page to UTF-8 encoding problem

1. Add a line at the beginning of the code:

header("Content-Type: text/html;charset=utf-8");

2. PHP file encoding problem:

Click the editor menu: "File"->"Save As" to see the encoding of the current file , make sure the file encoding is: UTF-8, if it is ANSI, you need to change the encoding to: UTF-8.

3. PHP file header BOM problem:

PHP files must not have BOM tags.

Otherwise, there will be a situation where the session cannot be used, and there will be a similar prompt:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent

This is because, when executing session_start(), the entire page cannot have output, but when due to There is a BOM tag in the previous PHP page.

PHP treats this BOM tag as output, so an error occurs!

So the PHP page must delete the BOM tag

How to delete this BOM tag:

(1) You can open the file with Dreamweaver and resave it, that is, you can remove the BOM Label!

(2) You can open the file with EditPlus, and in the menu "Preferences"->"File"->"UTF-8 Identity", set it to: "Always delete signature",

Then save the file and you can remove the BOM tag!

4. UTF-8 encoding problem when PHP saves a file as an attachment:

When PHP saves a file as an attachment, the file name must be GB2312 encoded. Otherwise, if there is In Chinese, garbled characters will be displayed.

If your PHP itself is a file in UTF-8 encoding format, you need to convert the file name variable from UTF-8 to GB2312:

iconv("UTF-8", "GB2312", "$filename");

5. When the article title is truncated and displayed, garbled characters appear. Or the question of "?" question mark:

Generally, when the article title is very long, part of the title will be displayed and the article title will be truncated, because a Chinese character in UTF-8 encoding format will occupy 3 characters of width. ,

When intercepting the title, sometimes only 1 character or 2 characters of width of a Chinese character will be intercepted. If the interception is not complete, garbled characters or "?" question marks will appear.

Use the following function to intercept the title, and there will be no problem:

function get_brief_str($str, $max_length) 
{ 
echo strlen($str) ."<br>"; 
if(strlen($str) > $max_length) 
{ 
$check_num = 0; 
for($i=0; $i < $max_length; $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; 
}

3. The problem of using UTF-8 encoding in the MYSQL database

1 .Create database and data table with phpmyadmin

When creating the database, please set "Organization" to: "utf8_general_ci"

Or execute the statement:

CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Create data table When: If the field stores Chinese, you need to set "Organization" to: "utf8_general_ci",

If the field stores English or numbers, the default is fine.

Corresponding SQL statement, for example:

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. Use PHP to read and write the database

After connecting to the database:

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

Add two lines:

mysql_query("set character set &#39;utf8&#39;");//读库
mysql_query("set names &#39;utf8&#39;");//写库

You can read and write the MYSQL database normally.

相关文章推荐:        
1.php页面中文乱码
相关视频推荐:
1.独孤九贱(4)_PHP视频教程

四、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]) < 128) 
$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。 

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。

在程序内,可以添加以下代码: 

System.useCodepage = true;

那么FLASH内所有字符都是使用GB2312的编码了,所有导入到FLASH或者从FLASH导出的数据,都应该做相应的编码转换。

The above is the detailed content of How to solve php Chinese garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use