PHP 頁面 <title> 中文顯示亂碼,本質是**瀏覽器編碼判斷錯誤**。解決核心:確保「文件保存編碼 = HTTP Content-Type 編碼 = Meta 聲明編碼 = 數據庫/輸出編碼」四者統一。本文給出標準化解決步驟與檢查清單。
在**任何輸出之前**發送正確的 Content-Type 頭,瀏覽器將無條件遵守。
<?php
// 必須在第一行,任何 echo/HTML/空白之前
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html>
<head>
<title>中文標題正常顯示</title>
...
放在 <head> **最開頭**,<title> 之前。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- HTML5 簡寫 -->
<meta charset="UTF-8">
<title>中文標題</title>
header() 失效、Session 啟動失敗、XML 解析錯誤。<?php
// PDO
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', $user, $pass);
// 或 mysqli
mysqli_set_charset($link, 'utf8mb4');
// 或 ThinkPHP 配置
'DB_CHARSET' => 'utf8mb4',
<?php
// 1. 最早發送 HTTP 頭
header('Content-Type: text/html; charset=UTF-8');
// 2. 啟動 Session(如需)
session_start();
// 3. 業務邏輯...
$title = '用戶中心 - 我的訂單';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>
<!-- CSS/JS -->
</head>
<body>
<h1><?php echo $title; ?></h1>
</body>
</html>
header('Content-Type: text/html; charset=UTF-8')?<meta charset="UTF-8"> 是否在 <head> 首行、<title> 之前?SET NAMES utf8mb4 / charset=utf8mb4?utf8mb4_general_ci?mb_internal_encoding('UTF-8')?charset?檢查 add_header Content-Type / AddDefaultCharset。<?php
class Charset
{
public static function init(string $charset = 'UTF-8'): void
{
// 1. PHP 內部編碼
mb_internal_encoding($charset);
mb_http_output($charset);
mb_http_input($charset);
mb_regex_encoding($charset);
// 2. HTTP 響應頭(僅在 CLI 以外)
if (php_sapi_name() !== 'cli' && !headers_sent()) {
header('Content-Type: text/html; charset=' . $charset);
}
// 3. 數據庫(需在連接後調用)
// self::setDbCharset($pdo, $charset);
}
}
// 入口文件最頂部調用
require 'Charset.php';
Charset::init('UTF-8');
中文亂碼 99% 是編碼不一致導致。**黃金法則:文件存 UTF-8 無 BOM → PHP 首行 header('Content-Type: text/html; charset=UTF-8') → HTML 首行 <meta charset="UTF-8"> → 數據庫連接 utf8mb4**。按此標準化配置,徹底告別亂碼。