简体   繁体   中英

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. 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:

{
   "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 .

By default, you can't use file_get_contents function to get the response content when the http status code is 400 .

You need to set ignore_errors options to 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 "<p>error: ", $json_output->error->{'message'}, " </p>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM