note 107107 deleted from function.json-decode by googleguy
| From: | googleguy@php.net | Date: | Fri, 14 Jun 2013 10:04:32 +0000 |
| Subject: | note 107107 deleted from function.json-decode by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195215@lists.php.net to get a copy of this message | ||
Note Submitter: juanloman at hilfetech dot com
----
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);
?>