[英]JSON element returning NULL
I am new to JSON and having a problem with checking at getting the error message when there is an error. 我是JSON新手,遇到错误时检查获取错误消息时遇到问题。 My code works fine when the result is not an error, so I do somewhat understand what I am doing.
当结果不是错误时,我的代码可以正常工作,因此我在某种程度上了解我在做什么。
This is the error JSON that I am trying to parse: 这是我尝试解析的错误JSON:
{
"error": {
"message": "Unsupported get request.",
"type": "GraphMethodException",
"code": 100
}
}
Here is my code that fails: 这是我失败的代码:
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
//valid $jsonurl = "http://graph.facebook.com/WhitworthACM";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
var_dump($json_output);
// This returns NULL
if (property_exists($json_output->error)) {
echo "<p>error: $json_output->error->{'message'} </p>";
} else {
echo "<p>no error :(</p>";
}
$facebook_id = $json_output->{'id'};
$facebook_name = $json_output->{'name'};
$facebook_link = $json_output->{'link'};
Because the url returns the 400 Bad Request
. 因为url返回
400 Bad Request
。
By default, you can't use file_get_contents
function to get the response content when the http status code is 400
. 默认情况下,当http状态代码为
400
时,不能使用file_get_contents
函数获取响应内容。
You need to set ignore_errors
options to true
. 您需要将
ignore_errors
选项设置为true
。
$opts = array(
'http'=>array(
'ignore_errors' => true
)
);
$context = stream_context_create($opts);
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
$json = file_get_contents($jsonurl, false, $context);
var_dump($json);
You can't chain multiple ->
's with string interpolation. 您不能使用字符串插值将多个
->
在一起。
You'll have resort to passing multiple arguments to echo
or to string concatenation: 您将不得不传递多个参数以进行
echo
或字符串连接:
echo "<p>error: ", $json_output->error->{'message'}, " </p>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.