Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 735
Epicurus Avatar asked Apr 19 '11 15:04

Epicurus


People also ask

How do I return a JSON response from REST API?

java as follows. Modify the DisplayEmployeeController. java. Add the headers="Accept=application/json", to tell the MVC to return Employee info in JSON format.

How do I return a JSON object to a REST web service?

Create RESTEasy Web Service to Produce JSON with @BadgerFish Now create a class whose methods will be exposed to the world as web service. Use JBoss @BadgerFish annotation that supports to return response as JSON. To return JSON as response we need to use media type as application/json.

Can PHP return JSON?

You can simply use the json_encode() function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header.

How do I POST JSON to a REST API endpoint?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.


1 Answers

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

like image 142
Just a PHP Programmer Avatar answered Nov 10 '22 12:11

Just a PHP Programmer