要让 PHP 脚本输出 UTF-8 编码的字符集,需要在代码中指定字符集为“UTF-8”。可以通过以下两种方法实现:
- 在脚本开头加上 header() 函数:
header("Content-Type: text/html; charset=utf-8");
- 使用 PHP 的内置函数 mb_internal_encoding() 设置字符集:
mb_internal_encoding("UTF-8");
无论哪种方法,都需要在代码中通过函数 mb_convert_encoding() 将其他编码格式的字符串转换成 UTF-8 编码:
// 将 GBK 编码的字符串转换成 UTF-8 编码
$str = "中国";
$str = mb_convert_encoding($str, "UTF-8", "GBK");
echo $str;
需要注意的是,如果是从数据库中取出数据,也需要将编码格式转换成 UTF-8。可以在连接 MySQL 数据库时,设置连接编码为 UTF-8:
// 设置 MySQL 连接编码为 UTF-8
$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");