note 107250 modified in function.json-encode by danbrown
| From: | danbrown@php.net | Date: | Thu, 10 May 2012 21:35:03 +0000 |
| Subject: | note 107250 modified in function.json-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-187910@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: <?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 ?>
--was--
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
http://php.net/manual/en/function.json-encode.php