note 107250 added to function.json-encode
| From: | julien dot dev at gmail dot com | Date: | Tue, 24 Jan 2012 18:08:56 +0000 |
| Subject: | note 107250 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-185731@lists.php.net to get a copy of this message | ||
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:
/* Imagine you have an object like this :
[{"name":"php help héhéhahéhé","url":"http://payAttention.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.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
----
Server IP: 89.31.146.176
Probable Submitter: 217.128.120.227
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/107250
Del: integrated -- https://master.php.net/note/delete/107250/integrated
Del: useless -- https://master.php.net/note/delete/107250/useless
Del: bad code -- https://master.php.net/note/delete/107250/bad+code
Del: spam -- https://master.php.net/note/delete/107250/spam
Del: non-english -- https://master.php.net/note/delete/107250/non-english
Del: in docs -- https://master.php.net/note/delete/107250/in+docs
Del: other reasons-- https://master.php.net/note/delete/107250
Reject -- https://master.php.net/note/reject/107250
Search -- https://master.php.net/manage/user-notes.php