note 107107 added to function.json-decode
| From: | juanloman at hilfetech dot com | Date: | Sat, 07 Jan 2012 20:38:36 +0000 |
| Subject: | note 107107 added to function.json-decode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-185452@lists.php.net to get a copy of this message | ||
I found that even though json_decode() takes UTF-8 strings, it won't parse if a Byte-Order-Mark
(BOM) is present.
Also, if you allow your users to edit JSON files, you end up with a mix of ASCII, ISO-8859-1, UTF-8
with and without BOM.
This function prepares a string for the JSON parser by converting it to UTF-8 and removing the BOM
if present.
<?php
function prepareJSON($input) {
//This will convert ASCII/ISO-8859-1 to UTF-8.
//Be careful with the third parameter (encoding detect list), because
//if set wrong, some input encodings will get garbled (including UTF-8!)
$imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1');
//Remove UTF-8 BOM if present, json_decode() does not like it.
if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3);
return $input;
}
//Usage:
$myFile = file_get_contents('somefile.json');
$myDataArr = json_decode(prepareJSON($myFile), true);
?>
----
Server IP: 69.147.83.197
Probable Submitter: 189.203.136.47
----
Manual Page -- http://www.php.net/manual/en/function.json-decode.php
Edit -- https://master.php.net/note/edit/107107
Del: integrated -- https://master.php.net/note/delete/107107/integrated
Del: useless -- https://master.php.net/note/delete/107107/useless
Del: bad code -- https://master.php.net/note/delete/107107/bad+code
Del: spam -- https://master.php.net/note/delete/107107/spam
Del: non-english -- https://master.php.net/note/delete/107107/non-english
Del: in docs -- https://master.php.net/note/delete/107107/in+docs
Del: other reasons-- https://master.php.net/note/delete/107107
Reject -- https://master.php.net/note/reject/107107
Search -- https://master.php.net/manage/user-notes.php