简体   繁体   中英

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. ie

$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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM