Fix Chinese Garbled Text in PHP
The main steps for solving Chinese garbled code issue in PHP are as follows:
- Add character encoding setting at the top of the PHP file.
header('Content-Type:text/html; charset=utf-8');
- Set the database character set when connecting to the database.
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");
- Convert the data to a specified character set before outputting it.
$data = "要输出的中文数据";
$data = mb_convert_encoding($data, "utf-8", "原始字符集");
echo $data;
- Set the character set of tables and fields to utf8 or utf8mb4 in MySQL database.
- Add character encoding settings in the tag of the HTML page.
<meta charset="utf-8">
The problem of garbled Chinese characters in PHP can be solved by using the above methods.