在使用php调用一些json接口文件时 如果使用 file_get_contents 获取页面json数据后
再使用json_decode()解析后 数据无法正常输出 这是的返回值为null
这是由于php的file_get_contents得到的数据前面有三个看不到的bom字符,将php转码或设置头部编码为无bom依旧无法解决
一种可行的办法就是:
$str = file_get_contents('json接口地址'); //获取页面地址$str = substr($str,3); //由于php问题file_get_contents得到的数据前面有三个看不到的bom字符 使用substr函数提取第三个字符后的内容$json = json_decode($str, true);//解析json代码 返回为 array 值echo $json['motd'];//以array 输出json中的 motd 数组
另外一种:
php$str = file_get_contents('json接口地址'); //获取页面地址$json = json_decode(trim($str,chr(239).chr(187).chr(191)),true); //chr(239).chr(187).chr(191)在输出时 组成了utf8文件的bom头,之后用trim函数将其移除print_r($json); //以array 输出json