您好,欢迎访问一九零五行业门户网

PHP中file_get_contents函数获取带BOM的utf-8,然后json_decode() 返回null的问题

问题:用php读取文件中的json数据,怎么解析都是返回null。
{a:1,b:2,x:[{c:3},{d:4},{e:5}]}
读取文件,使用了file_get_contents函数。
$json = '{a:1,b:2,x:[{c:3},{d:4},{e:5}]}'; var_dump(json_decode($json)); var_dump(json_decode($json, true));
如果直接在php中读取json字符串,是没有错的,怎么从文件读取就错了呢。
搜索得以下结果:
php: json_decode - manual
http://www.php.net/manual/zh/function.json-decode.php
php使用json_decode返回null ? 服务器运维与web架构
http://www.nginx.cn/337.html
php json_decode null - toeasy - 博客园
http://www.cnblogs.com/toeasy/archive/2012/04/09/2439688.html
json_decode() 得到null-夜色-yes-phpchina - powered by discuz!
http://bbs.phpchina.com/thread-267593-1-1.html
php5中file_get_contents函数获取带bom的utf-8文件内容时需注意 - wanglianghuaihua的日志 - 网易博客
http://wanglianghuaihua.blog.163.com/blog/static/54251531201091915210555/
关键结果在是后面两个。造成json_decode() 解析null的原因是,json文件是utf-8格式,带有bom。
修正后代码如下,即可正常解析。
$dmtext = file_get_contents( aroot .'data' . ds . 'dmtype.json.php'); if(preg_match('/^\xef\xbb\xbf/',$dmtext)) { $dmtext = substr($dmtext,3); } //trim $dmtext = t($dmtext); echo $dmtext; /* create array list from comments */ $dmlist = json_decode($dmtext,true); //当该参数为 true 时,将返回 array 而非 object 。 var_dump($dmlist);
显示结果:
view code { success: true, total:4, items: [ {id:1,c:asdaeg,tb: dm_suppliertype, cn: 供应商类型,tips:供应商类型}, {id:2,c:adsafr,tb: suppliertype2, cn: 供应商类型2,tips:供应商类型}, {id:3,c:ada222,tb: suppliertype3, cn: 供应商类型3,tips:供应商类型}, {id:4,c:23jetg,tb: suppliertype4, cn: 供应商类型4,tips:供应商类型} ]}array(3) { [success]=> string(4) true [total]=> string(1) 4 [items]=> array(4) { [0]=> array(5) { [id]=> string(1) 1 [c]=> string(6) asdaeg [tb]=> string(15) dm_suppliertype [cn]=> string(15) 供应商类型 [tips]=> string(15) 供应商类型 } [1]=> array(5) { [id]=> string(1) 2 [c]=> string(6) adsafr [tb]=> string(13) suppliertype2 [cn]=> string(16) 供应商类型2 [tips]=> string(15) 供应商类型 } [2]=> array(5) { [id]=> string(1) 3 [c]=> string(6) ada222 [tb]=> string(13) suppliertype3 [cn]=> string(16) 供应商类型3 [tips]=> string(15) 供应商类型 } [3]=> array(5) { [id]=> string(1) 4 [c]=> string(6) 23jetg [tb]=> string(13) suppliertype4 [cn]=> string(16) 供应商类型4 [tips]=> string(15) 供应商类型 } }}
其它类似信息

推荐信息