Home >Backend Development >PHP Problem >How to solve php Chinese garbled code under Linux
When developing PHP under Linux system, Chinese garbled characters are a common problem. The main reason is because Linux uses UTF-8 encoding by default, while PHP uses ISO-8859-1 encoding by default. When using Chinese characters, it will cause garbled characters.
This article will introduce common methods to solve the problem of Chinese garbled characters in PHP under Linux.
1. Set the character encoding in the PHP file
First, we can set the character encoding in the PHP code. In the first line of your PHP file, add the following code:
header('Content-Type:text/html;charset=utf-8');
This will tell the browser that the page uses UTF-8 encoding to display the content. Please note that this line of code must precede all HTML tags. Otherwise, it won't work.
2. Change the system default character encoding
We can also change the system default character encoding to be consistent with PHP’s encoding. Use the following command to change the default encoding:
sudo dpkg-reconfigure locales
Then select an appropriate encoding, such as UTF-8.
3. Change the Apache Web server encoding
The Apache Web server is part of the PHP operating environment. We can change the server encoding by modifying the Apache configuration file. Open the /etc/apache2/conf-enabled/charset.conf file and change the default encoding to be consistent with PHP:
AddDefaultCharset UTF-8
Please note that if you are using other web servers, such as Nginx, you need to configure Make similar changes in the file.
4. Change the PHP configuration file
Finally, we can change the PHP configuration file to change the default character encoding. On an Ubuntu or Debian system, open the /etc/php/
default_charset = "iso-8859-1"
Change it to UTF-8:
default_charset = "utf-8"
Save the changes and restart the Apache server for the changes to take effect.
Summary
Under Linux systems, it is very common to encounter Chinese garbled problems when developing using PHP. There are various ways to solve this problem, such as setting the character encoding in the PHP file, changing the system default character encoding, changing the Apache web server encoding, and changing the PHP configuration file. If you're still having problems, double-check your code and operating system settings to determine if there are any other issues.
The above is the detailed content of How to solve php Chinese garbled code under Linux. For more information, please follow other related articles on the PHP Chinese website!