2012-04-26 83 views
3

我有以下的数组:PHP:json_encode和json_decode使用UTF-8

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

(原始事件字符串是: “名人器官演奏 - 柔-维罗尼卡Cauchefer-Choplin” 与ENT_QUOTES,我用ヶ辆)

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

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

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

非常感谢!

+0

“我会得到这个在我的数据库”那是因为你是在救它错了。 – 2012-04-26 04:52:04

+0

你为什么'JSON_ENCODE'将某些东西保存到DB中? – Jakub 2012-04-26 04:53:16

+0

如果从phpmyadmin导出该特定行,您在.sql文件中获得了什么? – 2012-04-26 04:56:09

回答

2

在我看来,你不关心消毒在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正常