Home >Backend Development >PHP Problem >How to modify Chinese garbled characters in php

How to modify Chinese garbled characters in php

PHPz
PHPzOriginal
2023-04-04 13:59:11481browse

How to modify PHP Chinese garbled characters

If you often encounter the problem of Chinese garbled characters when using PHP to develop or deploy websites, then this article will help you solve this problem. The list is as follows:

  1. Confirm database encoding

First, you need to confirm whether the encoding of the database is correct. It is recommended to use UTF-8 encoding. You can confirm the database encoding in the following ways:

Open the MySQL command line tool and enter the following command in the MySQL command line:

show variables like 'character%';

This command will display the character set and proofreading set of the database. settings, making sure they are all correct.

  1. Modify PHP code

If your database encoding is set correctly, but Chinese garbled characters appear in the output, there may be a problem with your PHP code. Please follow the steps below to modify the PHP code:

  1. Set encoding

Add the following code at the top of the PHP file:

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

This code will set the character set is UTF-8.

  1. Modify the code for connecting to the database

When connecting to the MySQL database, use the following code:

$mysqli = new mysqli('localhost', 'username', 'password', 'database');
$mysqli->set_charset('utf8');

This code will set the character set of mysqli to UTF-8.

  1. Modify the SQL query statement

In the SQL query statement, use the following code:

$query = "SELECT * FROM `table` WHERE `name` LIKE '%{$keyword}%' COLLATE utf8_general_ci";

This code will set the character set of the SQL query statement is UTF-8.

  1. Modify the output code

In the output, use the following code:

echo mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8');

This code will convert the Chinese in the $str string into HTML entities, thereby avoiding the problem of Chinese garbled characters.

After modifying the above code, the problem of Chinese garbled characters should be solved.

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