【问题标题】:What is the best way to convert a string to UTF-8 in PHP?在 PHP 中将字符串转换为 UTF-8 的最佳方法是什么?
【发布时间】:2011-08-14 15:27:12
【问题描述】:

我想知道使用 PHP 将字符串转换为 UTF-8 的最佳方法是什么。

以下在页面上看起来不错,但在 MySQL 中有些字符看起来是乱码。

  • MYSQLUPGRADE EVENT – New Mazda2 from £124.99 per month. Representative 0% APR over 3 years. Min 50% deposit required. Call xxxxxxxxxxxx for test drive, info or Ts&Cs.
  • 在页面UPGRADE EVENT - New Mazda2 from £124.99 per month. Representative 0% APR over 3 years. Min 50% deposit required. Call xxxxxxxxxxxx for test drive, info or Ts&Cs.

我看过 iconv、mb_string、html_entity_decode、htmlentities、mb_convert_encoding 等。

数据库排序规则是 utf8_unicode_ci,表的字符集是 utf8。

【问题讨论】:

  • mb_convert_encoding 为我工作,你面临什么问题?
  • @Tobiask: mb_convert_encoding(htmlentities(html_entity_decode($string), ENT_QUOTES, 'ISO-8859-1'), "UTF-8", "UTF-8");是我用的

标签: php mysql encoding utf-8 string-conversion


【解决方案1】:

尝试使用mysql_query("SET NAMES 'utf8'")(或dbh->exec("SET NAMES 'utf8'"))设置连接的编码。

【讨论】:

  • SET NAMES 'utf8' 似乎不起作用。 if($this->dbh->exec("SET NAMES 'utf8'")) { if($this->dbh->exec("INSERT INTO .....")) { //do stuff } }
【解决方案2】:

你应该设置mysql连接的编码。尝试使用SET NAMES utf8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多