Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode JSON_UNESCAPED_SLASHES not working and still escaping slashes

My autocomplete search feature is broken because of how characters with accents are stored in the mySQL.

For example, in the mySQL column, É is stored like \u00c9

In the PHP, which receives the user's input and calls on mySQL, É is \xc3\x89

json_encode() almost works perfectly to take "\xc3\x89" and convert it to "\u00c9"

$clean = json_encode($criteria, JSON_UNESCAPED_SLASHES);

Except it converts it to "\\u00c9" and so the characters don't match even though they are both É.

The option JSON_UNESCAPED_SLASHES isn't working. Why does it not keep another backslash from being added in front of the backslash?

How do I get this to work?

Edit: I just added the actual code and error log output below. code:

error_log("criteria vvvvvvvvvvvvv");
error_log($criteria);

$clean = json_encode($criteria, JSON_UNESCAPED_SLASHES);  

error_log("json_encode(criteria) vvvvvvvvvvvvvv");
error_log($clean);

The error log:

[Fri Aug 23] criteria vvvvvvvvvvvvvvv, 
[Fri Aug 23 \xc3\x89
[Fri Aug 23] json_encode(criteria) vvvvvvvvvvvvvvv, 
[Fri Aug 23] "\\u00c9"
like image 633
Andrew Koper Avatar asked Oct 25 '25 05:10

Andrew Koper


1 Answers

First JSON_UNESCAPED_SLASHES is used to prevent escaping "SLASHES" / as the name implies, don't expect it to prevent escaping backslashes \

echo json_encode('/'); // prints "\/"
echo json_encode('/', JSON_UNESCAPED_SLASHES); // prints "/"
echo json_encode("\\", JSON_UNESCAPED_SLASHES); // prints "\\"
//note on line 3 : the input is 1 backslash

As you can see it prevents escaping slashes only , not backslashes

Regarding your problem, if you ended up by using json_encode with something like \\u00c9 then you must have gave it this string as input \u00c9 , json_encode() did nothing wrong , you feed it with the string "\u00c9" not the Unicode character00c9 and it escaped the backslash at the string beginning.

Your $criteria variable is probably holding a JSON encoded string like "\u00c9" that has been encoded without using the JSON_UNESCAPED_UNICODE option, in other words don't use json_encode() twice.

check these examples, it could clear things out

echo json_encode("É", JSON_UNESCAPED_SLASHES) . "\n";
echo json_encode("\u00c9", JSON_UNESCAPED_SLASHES) . "\n";
echo json_encode("\xc3\x89", JSON_UNESCAPED_SLASHES) . "\n";
echo json_encode("/") . "\n";
echo json_encode("/", JSON_UNESCAPED_SLASHES) . "\n";
echo json_encode("\\", JSON_UNESCAPED_SLASHES) . "\n";

This outputs

"\u00c9"
"\\u00c9"
"\u00c9"
"\/"
"/"
"\\"

live demo

like image 173
Accountant م Avatar answered Oct 26 '25 19:10

Accountant م