I have a REST web service written in PHP and I'm calling it using a POST request (making use of curl for this). The web service should return a JSON document. Problem is, I'm not sure what is the correct way to send this document back to the web service client. Is it sufficient to just echo it out?
Right now it looks like this is the only way in which i can get the JSON document to appear in the result of the POST request (the $result variable):
$result = curl_exec($ch);
3 Answers 3
You can format your result in Array or Object and then Just echo it with the json headers. i.e
$result_json = array('name' => 'test', 'age' => '16');
// headers for not caching the results
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 1997年7月26日 05:00:00 GMT');
// headers to tell that result is JSON
header('Content-type: application/json');
// send the result now
echo json_encode($result_json);
Hope this helps, Thanks
-
Thanx, adding those headers indeed solved the formatting problem I was having (my browser wouldn't recognize the file as valid a JSON document). I was also wondering if I could output XML as easily as JSON. However, I couldn't find an equivalent function to json_encode. Do you know if such a built-in function even exists?Epicurus– Epicurus2011年04月20日 14:17:21 +00:00Commented Apr 20, 2011 at 14:17
-
If you're wanting indented formatting in the returned JSON, you can change the last line to
echo json_encode($result_json, JSON_PRETTY_PRINT);
Hamman Samuel– Hamman Samuel2020年06月15日 05:26:47 +00:00Commented Jun 15, 2020 at 5:26
To get json result from php you should use
echo json_encode($result_json)
but echo does not exit the program so after using echo it is better to exit program but for shorthand you can use
exit(json_encode($result_json));
I've implemented it a few times and I was posting it just as string to the WS and echoing back from WS as response again as string. I used json_encode and json_decode functions for this...