Why my JSON string is null?

让人想犯罪 __ 提交于 2020-01-02 16:17:23

问题


I have written a code in PHP , to see the JSON string output. But i am getting null value.

<?php

 $l=array();

 $l[] = array('a'=>'@cÐaÐjÔÐ J kf _ÞÒi^ ','b'=>']éÞ[ѯРQtÍ]hà_ , `ËSÐ J heZ Òhi');

 echo $j = json_encode($l);

?>

Output-:

  [{"a":null,"b":null}] 

Why the JSON output is coming in null. I am expecting that there must be character encoding problem.

i want the output in following format.

[{"a":"@cÐaÐjÔÐ J kf _ÞÒi^","b":"]éÞ[ѯРQtÍ]hà_ , `ËSÐ J heZ Òhi"}] 

Please help me out. Please suggest me some solution

Thanks in Advance !!!


回答1:


You may need to use utf8_encode() the string before pushing to array and then json_encode since json_encode() works only only with utf8 encoded data

$l=array();

$l[] = array('a'=>utf8_encode('@cÐaÐjÔÐ J kf _ÞÒi^ '),
'b'=>utf8_encode(']éÞ[ѯРQtÍ]hà_ , `ËSÐ J heZ Òhi'));

echo json_encode($l);

Ok looks like your issue is not so simple,and you need to use

htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE); 

to handle the situation

$array = array("a"=>htmlentities( (string) "@cÐaÐjÔÐ J kf _ÞÒi^ ", ENT_QUOTES, 'utf-8', FALSE),
               "b"=>htmlentities( (string) "]éÞ[ѯРQtÍ]hà_ , `ËSÐ J heZ Òhi", ENT_QUOTES, 'utf-8', FALSE)

             );

$json = json_encode($array);
echo ($json);

check here http://phpfiddle.org/main/code/mh8-7ua

You need to add as above in your array elements.




回答2:


I've recreated your described behaviour using a limited encoding.

Check the file encoding of your php script. Make sure that it is set to unicode or utf8 if it is available.

Otherwise you'll have to convert your string to utf8 first like Abhik posted in his answer.

Your output will then look like

[{"a":"@c\u00d0a\u00d0j\u00d4\u00d0 J kf _\u00de\u00d2i^ ",
  "b":"]\u00e9\u00de[\u00d1\u00af\u00d0 Qt\u00cd]h\u00e0_ , `\u00cbS\u00d0 J heZ \u00d2hi"}]

That is working as intended, since...

Any character may be escaped. If the character is in the Basic
Multilingual Plane (U+0000 through U+FFFF), then it may be
represented as a six-character sequence: a reverse solidus, followed
by the lowercase letter u, followed by four hexadecimal digits that
encode the character's code point. The hexadecimal letters A though
F can be upper or lowercase. So, for example, a string containing
only a single reverse solidus character may be represented as
"\u005C".



来源:https://stackoverflow.com/questions/21645243/why-my-json-string-is-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!