In PHP development, it's common to encounter garbled characters when outputting Chinese text, which negatively impacts user experience. Mastering the correct encoding handling methods can effectively avoid garbled characters and ensure proper display of Chinese content. Below are several practical solutions.
First, ensure the PHP file itself is saved with UTF-8 encoding. Add the following header declaration at the beginning of your PHP script to explicitly tell the browser to interpret the page content as UTF-8:
<span class="fun">header('Content-Type: text/html; charset=UTF-8');</span>
This ensures the PHP file and its output content use consistent encoding, reducing the risk of garbled text.
If PHP reads Chinese data from a database, you must set the database connection character set to UTF-8 to ensure encoding consistency during data transmission. Example code:
$connection = mysqli_connect("localhost", "username", "password", "database");
mysqli_set_charset($connection, "utf8");
This effectively prevents garbled Chinese content retrieved from the database.
Before outputting any content in PHP, use the header function to set the Content-Type header to UTF-8 encoding to ensure the browser parses the page correctly:
<span class="fun">header('Content-Type: text/html; charset=UTF-8');</span>
This is a crucial step to prevent garbled characters on the webpage.
For strings with uncertain encoding, you can use mb_convert_encoding to convert them to UTF-8 encoding. Example:
$text = "中文内容";
$text = mb_convert_encoding($text, "UTF-8", "auto");
echo $text;
This ensures the output characters meet the page encoding requirements.
To prevent special HTML characters from interfering with Chinese display, use the htmlspecialchars function for escaping. Example:
$text = "<p>中文内容</p>";
echo htmlspecialchars($text);
This method protects the page structure integrity while avoiding garbled text issues.
The above techniques cover multiple aspects from file encoding, database connection, HTTP header settings, to string encoding conversion and HTML escaping. They form practical solutions to prevent garbled Chinese characters in PHP output. Developers can apply them flexibly according to specific needs to ensure stable and clear presentation of Chinese content on web pages.