Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode() escaping forward slashes

Tags:

json

php

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?

like image 646
Michael C. Avatar asked Apr 18 '12 13:04

Michael C.


People also ask

What is json_encode and Json_decode?

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.

Why are forward slashes escaped in JSON?

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.

What does the PHP function json_encode () do?

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.

What is json_encode in JavaScript?

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.


2 Answers

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.

like image 34
ThiefMaster Avatar answered Sep 25 '22 02:09

ThiefMaster


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/" 
like image 140
hakre Avatar answered Sep 24 '22 02:09

hakre