Home  >  Article  >  php教程  >  Solution to the problem of no data (empty) when php reads json

Solution to the problem of no data (empty) when php reads json

WBOY
WBOYOriginal
2016-07-11 08:43:411122browse

When using PHP to call some json interface files, if you use file_get_contents to obtain the page json data

After using json_decode() to parse, the data cannot be output normally. The return value is null

This is because there are three invisible BOM characters in front of the data obtained by PHP's file_get_contents. Transcoding PHP or setting the header encoding to no BOM still cannot solve the problem

One possible way is:

<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>

Another one:

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn