note 107250 deleted from function.json-encode by cmb
| From: | cmb@php.net | Date: | Sun, 04 Nov 2018 10:06:26 +0000 |
| Subject: | note 107250 deleted from function.json-encode by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-209609@lists.php.net to get a copy of this message | ||
Note Submitter: julien dot dev at gmail dot com
----
Guys, (and girls)
A trick to unescape UTF8 for ppl with php < 5.4.0
json_encode(...) gives you \\u..... right ?
json_decode DOES unescape though !
so:
<?php
/* Imagine you have an object like this :
[{"name":"php help héhéhahéhé","url":"http://payAttention.example.com"},{"name":"took
me brainack j'étais mal mec","url":"http://slashesEscapingSux"}]
*/
//first encode your object
$myDirtyString = $json_encode($myObject);
/*the JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE being unavailable, you'll have some
ugly escaping happening :
[{"name":"php help h\\u00e9h\\u00e9hah\\u00e9h\\u00e9","url":"http:\\/\\/payAttention.example.com"},{"name":"took
me brainack j'\\u00e9tais mal mec","url":"http:\\/\\/slashesEscapingSux\\/"}]
*/
//So, you'll have to unescape slashes:
$myDirtyString = str_replace("\\/","/",$myDirtyString);
//Then, for the trick, escape doule quotes
$myDirtyString = str_replace('"','\\\\"',$myDirtyString);
//in oder to json_decode this trciked string (and get your utf8 unescaped)
$myCleanedString = json_decode('"'.$myDirtyString.'"');
// Je tour est joué !
// There might be better ways to do it but i found so much useless nonsense on forums that i decided
to go with it for tonight
?>