michaellindahl
michaellindahl

Reputation: 2052

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'};

Upvotes: 2

Views: 269

Answers (2)

xdazz
xdazz

Reputation: 160833

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);

Upvotes: 1

user229044
user229044

Reputation: 239240

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>";

Upvotes: 0

Related Questions