Home > Mobile >  How to return {"a": "\u0002"} to browser in php?
How to return {"a": "\u0002"} to browser in php?

Time:11-06

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

CodePudding user response:

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

CodePudding user response:

\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"}

CodePudding user response:

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

exit(stripcslashes(json_encode($arr)));
?>
  •  Tags:  
  • php
  • Related