欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-06-10 23:12:07
...

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

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

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

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

一种可行的办法就是:

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

另外一种:

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1140692.htmlTechArticlephp读取json时无数据(为空)的解决方法,phpjson 在使用PHP调用一些json接口文件时 如果使用file_get_contents 获取页面json数据后 再使用json_decode(...
相关标签: json