今天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);