-1

I want to send some data to browser, I write code like below.

<?php
$arr = array('a'=> "\u0002 hello");

exit(json_encode($arr));
?>

and I get a result: enter image description here

but I wanna a result like below, \u0002 not \\u0002, what should I do? enter image description here

webber
  • 69
  • 5
  • 2
    `"\u0002"` in PHP is not the character with code 2 (why do you use it?) but a string that contains ``\``, `u` and the four digits. – axiac Nov 05 '21 at 12:07
  • 2
    Encoding your given data as JSON, _must_ escape this backslash. If you want to get only `\u0002` _in_ your JSON - well then you need to provide the _proper_ input data that json_encode would transform into this to begin with. – CBroe Nov 05 '21 at 12:09
  • What do you actually want to send? If you want a string that contains `\u0002` and you send it JSON encoded then the \ must be escaped. It's not clear though if your intention is to literally send `\u0002` or if you have some other character in mind – apokryfos Nov 05 '21 at 12:10
  • Relevant: https://stackoverflow.com/q/22745662/2943403 , https://stackoverflow.com/q/6771938/2943403 , https://stackoverflow.com/q/7381900/2943403 – mickmackusa Nov 08 '21 at 08:33

2 Answers2

2

"\u0002" in PHP is not the character with code 2 (why do you use it?) but a string that contains \, u and the four digits.

Use the chr() function to produce a character from its numeric code.

$arr = array('a'=> chr(2)." hello");
echo(json_encode($arr));

Check it online.

axiac
  • 68,258
  • 9
  • 99
  • 134
1

\u#### is JSON's unicode escape format, and has no meaning in a PHP string.

Using PHP's actual unicode escape:

$arr = array('a'=> "\u{0002} hello");

Or, since codepoints below 128 / 0x80 have single-byte representations, you can get away with:

$arr = array('a'=> "\x02 hello");

Both will produce the desired output: {"a":"\u0002 hello"}

Sammitch
  • 30,782
  • 7
  • 50
  • 77