Home  >  Article  >  Backend Development  >  How to solve the problem of Chinese garbled characters displayed in php files

How to solve the problem of Chinese garbled characters displayed in php files

藏色散人
藏色散人Original
2021-10-15 09:02:0916345browse

Solution to the problem that php files display Chinese garbled characters: 1. Add a header statement at the top of the PHP file; 2. Add utf-8 encoding at the beginning of the page; 3. Execute "mysql_query('SET NAMES UTF8 ');".

How to solve the problem of Chinese garbled characters displayed in php files

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

1: A mixed page of HTML and PHP Solution

How to mix HTML and PHP, in addition to following the first method, you also need to add this code at the top of the PHP file:

<?php
header("content-type:text/html;charset=utf-8");  //设置编码
 
?>

2: The problem of Chinese garbled characters in pure PHP pages (the data is static)

If your PHP page has garbled characters, you only need to Just add the following code at the beginning of the page.

<?php
header("content-type:text/html;charset=utf-8");  //设置编码
?>

Three: PHP Mysql Chinese garbled problem

In addition to following the third operation, you also need to Add database coding before querying/modifying/adding data. Moreover, it is worth noting that the UTF8 here is different from the previous one, there is no horizontal line in the middle.

<?php
 mysql_query(&#39;SET NAMES UTF8&#39;);
 //接下来的就是查出数据或者修改,增加
?>

If you are using MySQL version 4.1 or higher, you can set a character encoding after the link database operation, like the following

UTF-8 encoding is just one of the encodings. If you don’t want to use UTF-8 encoding, you can also use other encodings. Just replace UTF-8 with the encoding you want to use. Currently, GB2312 is mainly used in Chinese website development. and UTF-8 two encodings.

One thing to note: The mysql_query("set names 'coding'"); code added before the PHP program that needs to perform database operations must be consistent with the code. The PHP encoding is consistent. If the PHP encoding is gb2312, then the mysql encoding is gb2312. If it is utf-8, then the mysql encoding is utf8. In this way, garbled characters will not appear when inserting or retrieving data.

Recommended learning: "PHP video tutorial

The above is the detailed content of How to solve the problem of Chinese garbled characters displayed in php files. 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