编程语言
首页 > 编程语言> > PHP:带有UTF-8的json_encode和json_decode

PHP:带有UTF-8的json_encode和json_decode

作者:互联网

我有以下数组:

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

(原始事件字符串为:“名人器官演奏会–Sophie-VéroniqueCauchefer-Choplin”,我在ENT_QUOTES中使用了htmlentities)

当我使用json_encode时,事件字符串返回为NULL,并将其保存为MySQL中的空字符串.

如果我不使用htmlentities.我将在数据库中获得此​​信息:“名人器官演奏会u2013 Sophie-Vu00e9ronique Cauchefer-Choplin”.我使用了许多方法,但仍然无法将此字符串转换回原始值.

我真的需要一些帮助,希望您能给我一个解决方案,以便像json那样编码上面的UTF-8字符串,然后将其保存到MySQL,然后再解码回其原始格式.我搜索了一段时间,但仍然找不到解决方案.

非常感谢!

解决方法:

在我看来,您并不关心对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正常

标签:utf-8,json,php
来源: https://codeday.me/bug/20191201/2080610.html