【问题标题】:PHP: json_encode and json_decode with UTF-8PHP:使用 UTF-8 的 json_encode 和 json_decode
【发布时间】:2012-04-26 04:48:36
【问题描述】:

我有以下数组:

Array
(
    [1] => Array
        (
            [time] => 07:30
            [event] => Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin
        )
)

(原始事件字符串为:“Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin”,我使用带有 ENT_QUOTES 的 htmlentities)

当我使用 json_encode 时,事件字符串返回为 NULL,并在 MySQL 中保存为空字符串。

如果我不使用 htmlentities。我会在我的数据库中得到这个:“Celebrity Organ Recital u2013 Sophie-Vu00e9ronique Cauchefer-Choplin”。我使用了很多方法,但我仍然无法将这个字符串转换回原来的。

我真的需要一些帮助,我希望你能给我一个解决方案,将上面的 UTF-8 字符串编码为 json,然后将其保存到 MySQL,然后再解码回原来的。我搜索了一段时间,但仍然找不到解决方案。

非常感谢!

【问题讨论】:

  • "我会在我的数据库中得到这个" 那是因为你保存错了。
  • 你为什么要JSON_ENCODEing 一些东西要保存到数据库中!?
  • 如果你从 phpmyadmin 导出特定的行,你会在 .sql 文件中得到什么?
  • 你的mysql字符集是utf8_unicode_ci吗?
  • @nDudani: 这就是我得到的:{"1":{"time":"07:30","name":"Celebrity Organ Recital u2013 Sophie-Vu00e9ronique Cauchefer-Choplin"} }。如果我不使用 htmlentities。

标签: php json utf-8


【解决方案1】:

在我看来,您并不关心清理 sql 查询中的值 http://php.net/manual/en/function.mysql-real-escape-string.php

简单示例: 我们有结构表:

CREATE TABLE `test` (
    `text` VARCHAR(1024) NULL DEFAULT '0'
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB

还有 PHP 脚本

   header("Content-type:text/html;charset=utf8");
    $ar = array
        (
            1 => Array
                (
                    'time' => '07:30',
                    'event' => 'Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin'
                )
        );

    $mysqli = new mysqli('localhost','root', '', 'test');

    $mysqli -> query("INSERT INTO `test` (`text`) VALUES ('" . json_encode($ar) . "')"); // we not escape characters like \, ", '

// now we use mysqli::real_escape_string
    $mysqli -> query("INSERT INTO `test` (`text`) VALUES ('" . $mysqli -> real_escape_string(json_encode($ar)) . "')"); // here we escape characters

    $mysqli_result = $mysqli -> query("SELECT * FROM `test");
    while($result = $mysqli_result -> fetch_assoc()){
        var_dump(json_decode($result["text"],true));
    }

var_dump 的结果是:

array
  1 => 
    array
      'time' => string '07:30' (length=5)
      'event' => string 'Celebrity Organ Recital u2013 Sophie-Vu00e9ronique Cauchefer-Choplin' (length=68)

array
  1 => 
    array
      'time' => string '07:30' (length=5)
      'event' => string 'Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin' (length=63)

第二个var_dump正常

【讨论】:

    猜你喜欢
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多