solomon_wzs
solomon_wzs

Reputation: 1711

json_decode in php process some special character

Here is the php code:

$str='{"key":"'.chr(1).'"}';
$json=json_decode($str);

json_decode return null. So how should I process the $str in order to decode. (P.S. $str here is just a example, it may include chr(2), chr(10) and so on).

Upvotes: 1

Views: 1150

Answers (2)

Cal
Cal

Reputation: 7157

As Gumbo points out, you are not generating valid JSON. If you must do this (unsure why, your example is basic a no-op), then use json_encode():

$str = '{"key":'.json_encode(chr(1).chr(2)).'}';
$json = json_decode($str);

This creates valid JSON:

{"key":"\u0001\u0002"}

And will decode correctly.

Upvotes: 1

Gumbo
Gumbo

Reputation: 655239

Only characters in the range U+0020-U+0021, U+0023-U+005B, U+005D-U+10FFFF may appear unescaped in strings. Any other character must be escaped using the Unicode escape sequence. In your case use \u0001 instead.

Upvotes: 3

Related Questions