Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当URL中的数据很小时,JSON对象为空?_Php_Json - Fatal编程技术网

Php 当URL中的数据很小时,JSON对象为空?

Php 当URL中的数据很小时,JSON对象为空?,php,json,Php,Json,我有一个JSON对象,我正在从如下url解码: $var = json_decode(file_get_contents($url), true); 我得到的数据来自新的battle.net API,该API作为包含字符数据的JSON对象返回 这里是一个实际的链接,在该链接中可以找到该字符,并且有要生成的数据: 现在,这里有一个不存在的字符链接,该字符生成错误: 错误作为包含“status”和“reason”属性的JSON对象返回。“状态”属性的值将始终为“nok” 我的问题是,当

我有一个JSON对象,我正在从如下url解码:

    $var = json_decode(file_get_contents($url), true);
我得到的数据来自新的battle.net API,该API作为包含字符数据的JSON对象返回

  • 这里是一个实际的链接,在该链接中可以找到该字符,并且有要生成的数据:
  • 现在,这里有一个不存在的字符链接,该字符生成错误:
错误作为包含“status”和“reason”属性的JSON对象返回。“状态”属性的值将始终为“nok”

我的问题是,当未找到该字符时,JSON对象$var为NULL,如果找到该字符,则JSON对象$var包含正确的数据。我需要能够检查状态是否为“nok”,以便输出适当的错误消息

我有:

  • 检查链接以确保它们正确生成
  • json\u解码(file\u get\u contents($url),true)
    更改为:
    json\u解码(file\u get\u contents($url),false)
    并尝试将$var作为对象访问
  • 尝试使用cURL而不是
    file\u get\u contents($url)

我在battle.net API论坛上发布了帖子,但我想我也会在这里尝试。

这是因为页面字符Not Found page返回一个
404 Not Found
HTTP响应代码,这很有意义,但被认为是一个错误

在HTTP流包装器上遇到错误(404500等)时,默认情况下,文件函数(如
File\u get\u contents
)将返回
false

为了忽略错误并返回内容,以便
json\u decode
能够解析它,您需要使用上下文:

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true),
));

$var = json_decode(file_get_contents($url, false, $context), true);

太棒了,谢谢,我读过关于使用流上下文的文章,但我没有发现任何似乎相关的东西。