I have a rest api created in php. Sharing a sample here:
public function getApiData(){
$returnData = ["a"=>"A","b"=>"B"];
header("Content-Type: application/json");
// I want to return the data in the json format for which i have two options.
// Option 1:
return $returnData
// Option 2 (if i don't use the option 1 to return):
#jsonResponse = json_encode($returnData,JSON_FORCE_OBJECT);
print_r($jsonResponse);
}
For the option 1 the response is JSON but its just a string for ex:
"{\"a\":\"A\",\"b\":\"B.\"}"
For the option 2 the response is JSON but it's appended with square opening and closing bracket. ex:
{
"a":"A",
"b":"B"
}[]
Notice that there is an opening and closing bracket in the end. If i use die()
or exit;
after the print_r statement then those square brackets are remove. But the problem is that i don't want to use both of them.
Is there any option to send pure JSON object in the response of rest API?