Question

  $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.

Was it helpful?

Solution

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

OTHER TIPS

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

That's probably a security-feature. The escaped version (Eg. the output) would be parsed as similar to the unescaped-version, by Javascript (Eg. \/ becomes /). Having escaped the slash like that, there is a lesser chance of the browser misinterpreting the Javascript-string as HTML. Of course, if you treat the data correct, this shouldn't be needed, so it's more a safeguard against a clueless programmer messing things up for himself.

Your input is not valid JSON, but PHP's JSON parser (like most JSON parsers) will parse it anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top