Home > Backend Development > PHP Tutorial > Solution to the problem of no data (empty) when php reads json, phpjson_PHP tutorial

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

WBOY
Release: 2016-07-11 10:36:19
Original
1450 people have browsed it

The solution to the problem of no data (empty) when php reads json, phpjson

When using PHP to call some json interface files, if you use file_get_contents to get 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><?php<br />$str</span> = <span>file_get_contents</span>('json接口地址'); <span>//</span><span>获取页面地址</span>
<span>$str</span> = <span>substr</span>(<span>$str</span>,3); <span>//</span><span>由于php问题file_get_contents得到的数据前面有三个看不到的BOM字符 使用substr函数提取第三个字符后的内容</span>
<span>$json</span> = json_decode(<span>$str</span>, <span>true</span>);<span>//</span><span>解析json代码 返回为 array 值</span>
<span>echo</span> <span>$json</span>['motd'];<span>//</span><span>以array 输出json中的 motd 数组</span>
Copy after login

Another one:

<?<span>php
</span><span>$str</span> = <span>file_get_contents</span>('json接口地址'); <span>//</span><span>获取页面地址</span>
<span>$json</span> = json_decode(<span>trim</span>(<span>$str</span>,<span>chr</span>(239).<span>chr</span>(187).<span>chr</span>(191)),<span>true</span>); <span>//</span><span>chr(239).chr(187).chr(191)在输出时 组成了utf8文件的bom头,之后用trim函数将其移除</span>
<span>print_r</span>(<span>$json</span>); <span>//</span><span>以array 输出json</span>
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1140692.htmlTechArticleSolution to no data (empty) when php reads json, phpjson uses PHP to call some json interface files If you use file_get_contents to obtain the page json data, then use json_decode(...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template