Home >Backend Development >PHP Tutorial >Solution to the problem of no data (empty) when php reads json, phpjson_PHP tutorial
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>
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>