Returning a JSON result from a PHP REST web service

21,583

Solution 1

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

Solution 2

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));
Share:
21,583
Epicurus
Author by

Epicurus

Updated on June 15, 2020

Comments

  • Epicurus
    Epicurus almost 4 years

    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);
    
  • Epicurus
    Epicurus about 13 years
    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?
  • Hamman Samuel
    Hamman Samuel almost 4 years
    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);