Asur
Asur

Reputation: 387

Print JSON and terminate execution for more detailed error reports

I would like to know if there is any way to print a JSON in a die function like this:

die(json_encode($response));  

Of course I've tested that and is not working as expected because it requires a string, I don't want to parse the JSON, I want to echo it as it is.

I have also thought about a custom function like:

public function reportError ($errorFlag, $message){
  $response = array($errorFlag, $message, $mysqli->error);
  echo json_encode($response);
  die ("");
}  

But I'm not sure if it is a good way to do it or there is something more simple. I'm normally pretty worried about good practices but I'm lost with this issue.

Any guidance is appreciated, thank you in advance.

Upvotes: 1

Views: 71

Answers (1)

ImClarky
ImClarky

Reputation: 1953

Use print_r() inside of your die().

print_r() has an optional second parameter, that if set to true returns the result as a string, rather than printing the result. So something like this should work:

die(print_r(json_encode($response), true));

Upvotes: 1

Related Questions