Returning a JSON result from a PHP REST web service
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);
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: Mon, 26 Jul 1997 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
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...
精彩评论