我有一个用PHP编写的REST Web服务,我使用POST请求(为此使用curl)来调用它。 Web服务应返回JSON文档。
问题是,我不确定将此文档发送回Web服务客户端的正确方法是什么。仅仅 echo 就足够了吗?
现在看来,这是我可以使JSON文档出现在POST请求($ result变量)的结果中的唯一方法:
$result = curl_exec($ch);
最佳答案
您可以将结果格式化为Array或Object,然后仅用json header 将其回显。
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);
希望这会有所帮助,谢谢