How to remove the (\)
backslash on a string? when using echo json_encode()
?
For example:
<?php $str = "$(\"#output\").append(\"<p>This is a test!</p>\")"; echo json_encode($str); ?>
note: When you echo $str, there will be no problem... but when you echo out using json_encode()
, the (\)
backslash will show up.
Is there a way to solve this?
Replace slash everywhere in the string----------->str =str. replace(/\//g,""); You can convert back to JSON object again using-->var output =JSON. parse(str);
Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.
The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Syntax : string json_encode( $value, $option, $depth ) Parameters: $value: It is a mandatory parameter which defines the value to be encoded.
json_encode($response, JSON_UNESCAPED_SLASHES);
Since PHP 5.4 there are constants which can be used by json_encode()
to format the json reponse how you want.
To remove backslashes use: JSON_UNESCAPED_SLASHES
. Like so:
json_encode($response, JSON_UNESCAPED_SLASHES);
View the PHP documentation for more constants and further information:
http://php.net/manual/en/function.json-encode.php
List of JSON constants:
http://php.net/manual/en/json.constants.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With