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:
file_put_contents($cache,json_encode($results));
When I open the cache file all my forward slashes "/" are being escaped:
http:\/\/distilleryimage4.instagram.com\/410e7...
I gather from my searches that json_encode()
automatically does this...is there a way to disable it?
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
This is because HTML does not allow a string inside a <script> tag to contain </ , so in case that substring's there, you should escape every forward slash.
PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable. We demonstrate on this page with single level arrays. Other pages demonstrate using json_encode with multi-dimensional arrays and scalar values.
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.
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
<?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/"
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