php json_decode utf8,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,然后再解码回其原始格式.我搜索了一段时间,但仍然找不到解决方案.

非常感谢!

解决方法:

简单的例子:

我们有具有结构的表:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值