json_encode() escaping forward slashes
is there a way to disable it?
Yes, you only need to use the JSON_UNESCAPED_SLASHES
flag.
!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)
json_encode($str, JSON_UNESCAPED_SLASHES);
If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).
<?php/* * Escaping the reverse-solidus character ("/", slash) is optional in JSON. * * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP. * * @link http://stackoverflow.com/a/10210433/367456 */ $url = 'http://www.example.com/';echo json_encode($url), "\n";echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";
Example Output:
"http:\/\/www.example.com\/""http://www.example.com/"
Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script>
tags it's necessary as a </script>
anywhere - even inside a string - will end the script tag.
Depending on where the JSON is used it's not necessary, but it can be safely ignored.
On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -
my expected:
http://localhost/api/v1/admin/logs/testLog.log
would be encoded to:
http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log
If you need to do a comparison, transforming the url using:
addcslashes($url, '/')
allowed for the proper output during my comparisons.