php读取json时无数据(为空)的解决方法

时间:2016-07-10 16:31:15   收藏:0   阅读:351

在使用PHP调用一些json接口文件时 如果使用 file_get_contents 获取页面json数据后 

再使用json_decode()解析后 数据无法正常输出 这是的返回值为null

这是由于php的file_get_contents得到的数据前面有三个看不到的BOM字符,将php转码或设置头部编码为无BOM依旧无法解决

一种可行的办法就是:

<?php
$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

 

原文:http://www.cnblogs.com/hanqishihu/p/5657787.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!