Rutger Huijsmans Rutger Huijsmans - 10 months ago 62
JSON Question

Return JSON using PHP

Currently I'm returning a message from my PHP backend like so:

$data = [ 'message' => 'Number doesn\'t exist!'];
$this->set_response(json_encode($data), REST_Controller::HTTP_CREATED);

This will create a message looking like this:

"{\"message\":\"Number doesn't exist!\"}"

I however am hoping to get a message looking like this:

"message": "Number doesn't exist!"

What am I doing wrong?

Answer Source

You can use JSON_UNESCAPED_SLASHES as second parameter in json_encode().

$data = [ 'message' => 'Number doesn\'t exist!'];
$encoded = json_encode($data,JSON_UNESCAPED_SLASHES);
$this->set_response($encoded, REST_Controller::HTTP_CREATED);

Other Solution:

$data = [ 'message' => 'Number doesn\'t exist!'];
$string = $this->set_response(json_encode($data), REST_Controller::HTTP_CREATED); // your current result
$decode = json_decode($string,true); // decode the value 
echo json_encode($decode,JSON_UNESCAPED_SLASHES); //and use JSON_UNESCAPED_SLASHES in json_encode()