首页 > Web开发 > 详细

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

时间:2016-07-07 00:51:06      阅读:280      评论:0      收藏:0      [点我收藏+]

在使用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

 

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

原文:http://www.cnblogs.com/wyp175/p/php-json_decode-null.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!