php怎么解析utf-8带BOM编码的json数据,php解析json数据返回NULL
2013-11-28 14:40
495 查看
今天遇到一个问题,json_decode解析json数据返回null,试了各种方法都不行,最后发现,原来是json文件编码的问题。
当json_decode解析utf-8带BOM格式的json数据时,会返回null。
json_decode函数能够接收utf8编码的参数,但是当参数中包含BOM时,json_decode就会失效。
这个函数能将给定的字符串转换成UTF-8编码,移除其中的BOM。
下面是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); 来源于:http://phpcode8.com/?p=555
相关文章推荐
- PHP中file_get_contents函数获取带BOM的utf-8,然后json_decode() 返回null的问题
- PHP中file_get_contents函数获取带BOM的utf-8,然后json_decode() 返回null的问题
- PHP中file_get_contents函数获取带BOM的utf-8,然后json_decode() 返回null的问题
- IOS请求php返回的数据JSON数据无法正确解析 utf-8格式
- PHP json_decode的坑 仅仅支持utf-8编码的字符,gbk编码会返回null
- 带BOM的utf-8,用json_decode() 返回null的问题 --- 超过3个bom字符
- PHP json_decode返回null解析失败原因
- Sencha touch 与PHP 怎么进行json 数据解析
- php解析请求url并返回json数据
- Android的okhttp的post请求,php返回json数据。以及遇到的okhttp dispatcher问题,和json解析遇到的问题
- js解析php返回的json数据无法获取length的问题分析
- 玩转Web之Json(三)-----easy ui怎么把前台显示的dataGird中的所有数据序列化为json,返回到后台并解析
- easy ui怎么把前台显示的dataGird中的所有数据序列化为json,返回到后台并解析
- php 获取并解析哈工大ltp-cloud返回的json数据
- 玩转Web之Json(三)-----easy ui怎么把前台显示的dataGird中的所有数据序列化为json,返回到后台并解析
- PHP json_decode返回null解析失败原因
- Java使用百度API 返回JSON数据为unicode编码,怎么转化为中文?
- PHP json_decode返回null解析失败原因
- 玩转Web之Json(三)-----easy ui怎么把前台显示的dataGird中的所有数据序列化为json,返回到后台并解析
- PHP中遇到BOM、<feff>编码导致json_decode函数无法解析问题