<?php
// 必須在任何輸出前呼叫
header('Content-Type: text/html; charset=utf-8'); // UTF-8
header('Content-Type: text/html; charset=gb2312'); // GBK/GB2312
header('Content-Type: text/html; charset=big5'); // Big5
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
# httpd.conf
AddDefaultCharset UTF-8
header('Content-Type: ...; charset=UTF-8')。header() > AddDefaultCharset > <meta>。<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$pdo->exec("SET NAMES 'utf8'"); // 或 utf8mb4
// mysqli
$mysqli->set_charset('utf8');
utf8mb4 完整支援 Emoji 與補充字元。| 層級 | 設定位置 | 範例值 |
|---|---|---|
| 資料庫/資料表/欄位 | 建立時指定 CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
utf8mb4 |
| HTML 頁面輸出 | PHP header() 或 <meta> |
utf-8 |
| PHP/HTML 檔案儲存編碼 | 編輯器「另存新檔」編碼選項 | UTF-8 (無 BOM) |
三者必須完全一致,否則會產生亂碼。
前端通常以 UTF-8 傳送。若後端為 GBK,需轉碼:
$content = iconv('UTF-8', 'GBK//IGNORE', $_POST['content']);
// 或使用 mb_convert_encoding()
$content = mb_convert_encoding($_POST['content'], 'GBK', 'UTF-8');
<?php
declare(encoding='UTF-8'); // PHP 5.3+,影響編譯器解讀字串字面值
?>
utf8mb4?SET NAMES utf8mb4?header('Content-Type: text/html; charset=utf-8')?<meta charset="utf-8"> 作為備援?AddDefaultCharset 已註解?遵循上述步驟,可徹底杜絕編碼亂碼問題。