Heim  >  Artikel  >  php教程  >  php读取json时无数据(为空)的解决方法

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

WBOY
WBOYOriginal
2016-07-11 08:43:411123Durchsuche

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

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn