Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain this PHP code using json_encode and json_decode?

Tags:

json

php

  $a = '{ "tag": "<b></b>" }';
  echo json_encode( json_decode($a) );

This outputs:

{"tag":"<b><\/b>"}

when you would think it would output exactly the input. For some reason json_encode adds an extra slash.

like image 487
user19087 Avatar asked Apr 07 '26 19:04

user19087


2 Answers

Because it's part of the JSON standard

http://json.org/

char

any-Unicode-character-
    except-"-or-\-or-
    control-character
\"
\\
\/ <---- see here?
\b
\f
\n
\r
\t
\u four-hex-digits
like image 199
Peter Bailey Avatar answered Apr 09 '26 12:04

Peter Bailey


use this:

echo json_encode($a,JSON_HEX_TAG)

Result will be:

["\u003C\u003E"]

You can read this article to improve your knowledge about JSON_ENCODE http://php.net/manual/en/function.json-encode.php

like image 36
symi khan Avatar answered Apr 09 '26 11:04

symi khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!