首页  >  文章  >  php教程  >  php读取json时无数据(为空)的解决方法

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

WBOY
WBOY原创
2016-07-11 08:43:411123浏览

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

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

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

一种可行的办法就是:

<span style="color: #800080;"><?php <br />$str</span> = <span style="color: #008080;">file_get_contents</span>('json接口地址'); <span style="color: #008000;">//</span><span style="color: #008000;">获取页面地址</span>
<span style="color: #800080;">$str</span> = <span style="color: #008080;">substr</span>(<span style="color: #800080;">$str</span>,3); <span style="color: #008000;">//</span><span style="color: #008000;">由于php问题file_get_contents得到的数据前面有三个看不到的BOM字符 使用substr函数提取第三个字符后的内容</span>
<span style="color: #800080;">$json</span> = json_decode(<span style="color: #800080;">$str</span>, <span style="color: #0000ff;">true</span>);<span style="color: #008000;">//</span><span style="color: #008000;">解析json代码 返回为 array 值</span>
<span style="color: #0000ff;">echo</span> <span style="color: #800080;">$json</span>['motd'];<span style="color: #008000;">//</span><span style="color: #008000;">以array 输出json中的 motd 数组</span>

 另外一种:

<span style="color: #000000;">php
</span><span style="color: #800080;">$str</span> = <span style="color: #008080;">file_get_contents</span>('json接口地址'); <span style="color: #008000;">//</span><span style="color: #008000;">获取页面地址</span>
<span style="color: #800080;">$json</span> = json_decode(<span style="color: #008080;">trim</span>(<span style="color: #800080;">$str</span>,<span style="color: #008080;">chr</span>(239).<span style="color: #008080;">chr</span>(187).<span style="color: #008080;">chr</span>(191)),<span style="color: #0000ff;">true</span>); <span style="color: #008000;">//</span><span style="color: #008000;">chr(239).chr(187).chr(191)在输出时 组成了utf8文件的bom头,之后用trim函数将其移除</span>
<span style="color: #008080;">print_r</span>(<span style="color: #800080;">$json</span>); <span style="color: #008000;">//</span><span style="color: #008000;">以array 输出json</span>

 

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn