Why does json_encode space bar add it to the array?

I skipped this behavior in PHP 5.6 (also identical in PHP 5.4 to 7.0).

$note = new SimpleXMLElement('<Note></Note>'); $note->addChild("string0", 'just a string'); $note->addChild("string1", "abc\n\n\n"); $note->addChild("string2", "\tdef"); $note->addChild("string3", "\n\n\n"); $note->addChild("string4", "\t\n"); $json = json_encode($note, JSON_PRETTY_PRINT); print($json); 

Outputs:

 { "string0": "just a string", "string1": "abc\n\n\n", "string2": "\tdef", "string3": { "0": "\n\n\n" }, "string4": { "0": "\t\n" } } 

There must be a reason for this behavior, I would like to understand. And also, if you know a way to make it behave the same for lines of texts and spaces, I would appreciate if you share your ideas!

Change Here is a snippet you can run: http://sandbox.onlinephpfunctions.com/code/d797623553c11b7a7648340880a92e98b19d1925

+5
source share
1 answer

This comes from RFC 4627 (highlighted by me)

All Unicode characters may be enclosed in quotation marks , with the exception of characters that must be escaped : quotation mark, inverse solidus, and control characters (U + 0000 - U + 001F) .

Newline ( \n ) is U+000A in UTF-8, so PHP faithfully converts it back to the corresponding JS equivalent

PHP uses this RFC for json_encode

PHP implements a superset of JSON, as stated in the original "RFC 4627 - it also encodes and decodes scalar types and NULL.

As I noted in the comments, all versions of PHP, starting with 5.2, do it this way ( Demo )

+1
source

All Articles