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:

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?


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, eg 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/"

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.

链接地址: http://www.djcxy.com/p/47922.html

上一篇: 如何在Java中使用Java字符串文字?

下一篇: 编码()转义正斜杠