【问题标题】:Store and output text with accents存储和输出带有重音符号的文本
【发布时间】:2016-04-30 02:43:45
【问题描述】:

我在数据库中有一些文本。我使用法语和英语。法语有口音和一些特殊字符,如ç。我使用 Mamp、MySQL 和 PHP。

我有排序规则latin1_swedish-ci(默认)。我试过utf8_general_ci,结果是一样的。 如果我在 html 页面中使用,我会在脑海中看到这个:<meta charset="UTF-8">

例如,在数据库中我有“voilà”。

当我将文本从数据库回显到 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à
}
  1. 为什么htmlentities 不起作用?
  2. utf8_encode(); 是要走的路吗?当我从数据库输出一些东西时,我必须总是使用它吗?如果排序规则已经是UTF8,为什么我必须使用它?有没有更好的方法在 MySQL 数据库中存储和输出带有重音符号的文本?

【问题讨论】:

  • @ItsGreg。另一个不回答我的问题。我得到了一个类似的解决方案,但问题是为什么
  • 如果您的字符串是voilàhtmlentities() 不应返回任何内容。 phpMyAdmin 中的字段是什么样的?
  • @rybo111:在 phpMyAdmin 我只有那个:瞧。只是为了测试。为什么它什么都不返回?
  • 您可以在查询之前尝试mysqli_set_charset($con,"utf8");$con 是您的连接吗?

标签: php mysql html-entities


【解决方案1】:

连接到数据库后,您应该将客户端字符集设置为 UTF8:

mysqli_set_charset($con, "UTF8");

否则 mysql 客户端会将 UTF8 'voilà' 转换为 latin1(因为它似乎是默认设置)。

要么告诉客户我想要 UTF8 中的所有内容,要么使用默认的 latin1 获取它,然后自己调用 utf8_encose($text) 将其逐个转换

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    相关资源
    最近更新 更多