json_encode() escaping forward slashes


I'm pulling JSON from Instagram:

$instagrams = json_decode($response)->data;

Then parsing variables into a PHP array to restructure the data, then re-encoding and caching the file:


When I open the cache file all my forward slashes "/" are being escaped:


I gather from my searches that json_encode() automatically does this...is there a way to disable it?

This question is tagged with php json

~ Asked on 2012-04-18 13:24:23

The Best Answer is


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

Example Demo

 * 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:


~ Answered on 2012-04-18 13:29:37


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.

~ Answered on 2012-04-18 13:25:44

Most Viewed Questions: