PHP中JSON_ENCODE 特殊字符encode 后 为 null问题_莫枫恋_新浪博客

今天json_encode一串字符后,发现结果却是NULL。google了一下结果发现JSON_ENCODE 应该算是一个BUG。

解决方法就是在JSON_encode之前先对字符串做 htmlentities 或者 urlencode 就可以了。然后json_decode 的时候做反向解码就行了。

解决方案在下面帖子里找到的

http://bugs.php.net/bug.php?id=49588

2009-09-18 10:36 UTC] fernando at consultorpc dot com

Description:
————
At my specific case, if a string contains an Euro symbol ( � ), json_encode will return null for that string.

It might also happens with other special characters.

Reproduce code:
—————

$array = array(
'name' => htmlentities( ‘My euro symbol �.’ )
);

var_dump( $array );
var_dump( json_encode( $array ) );

Expected result:
—————-
array(1) {
["name"]=>
string(29) “My euro symbol €.”
}
string(13) “{“name”:”My euro symbol €.”}”

Actual result:
————–
array(1) {
["name"]=>
string(29) “My euro symbol â?¬.”
}
string(13) “{“name”:null}”

[2010-04-01 13:13 UTC] arievanziel at gmail dot com

json_encode returns null for a string with é or (for example) ä in it.

Reproduce code:

$test = “é”;
echo $test;
echo json_encode($test);

A possible workaround could be to use (especially if you will use the
json_encode string as html output):

$test = “é”;
$test = htmlentities($test, UTF-8);
echo $test;
echo json_encode($test);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值