5

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);
asked Apr 19, 2011 at 15:48

3 Answers 3

23

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

answered Apr 19, 2011 at 16:10
2
  • 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? Commented 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); Commented Jun 15, 2020 at 5:26
1

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));
answered Jun 14, 2019 at 14:05
0

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

answered Apr 19, 2011 at 15:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.