Anshuman Pattnaik
Anshuman Pattnaik

Reputation: 933

Why my JSON string is null?

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 !!!

Upvotes: 2

Views: 882

Answers (2)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

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.

Upvotes: 1

Bjoern
Bjoern

Reputation: 16314

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".

Upvotes: 0

Related Questions