php返回数据带bom,php如何解析utf-8带BOM编码的json数据,php解析json数据返回NULL

今天遇到一个问题,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值