我在数据库中有一些文本。我使用法语和英语。法语有口音,还有一些特殊字符,如ç
。我使用Mamp,MySQL和PHP。
我有排序规则latin1_swedish-ci
(默认值)。我试了utf8_general_ci
,结果是一样的。如果我在 html 页面中使用,我会在头上有这个:<meta charset="UTF-8">
例如,在数据库中,我有"瞧"。
当我将数据库中的文本回显到 html 时:
$con = mysqli_connect("localhost","root","root");
if (!$con) {
die('The connexion failed: ' . mysqli_error());
}
if (!mysqli_select_db($con, 'prova')){
echo "Connection with database was not possible";
}
$result = mysqli_query($con, "SELECT * FROM test1
WHERE id='1' ")
or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
$text = $row['first'];
echo $text; //I see: voil�
echo htmlentities($text); //I see nothing
echo utf8_encode($text); //This works: I see voilà
}
- 为什么
htmlentities
不起作用? utf8_encode();
是要走的路吗?当我从数据库输出一些东西时,我必须始终使用它?如果排序规则已经UTF8
,为什么我必须使用它?有没有更好的方法在 MySQL 数据库中存储和输出带有重音符的文本?
连接到数据库后,应将客户端字符集设置为 UTF8:
mysqli_set_charset($con, "UTF8");
否则,mysql 客户端会将 UTF8 'voilà' 转换为 latin1('因为这似乎是默认值)。
要么你告诉客户端我想要 UTF8 中的所有内容,要么你用默认的 latin1 获取它,然后自己调用 utf8_encose($text) 逐个转换它